package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.gather.config.UrlConfig;
import com.erp.gather.domain.*;
import com.erp.gather.domain.bo.ErpCollectProductBo;
import com.erp.gather.domain.vo.*;
import com.erp.gather.mapper.*;
import com.erp.gather.service.*;
import com.erp.gather.utils.ChatGptUtils;
import com.ruoyi.ae.api.RemoteAeProductService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.PublishType;
import com.ruoyi.common.core.utils.CommonUtils;
import com.ruoyi.common.core.utils.ImageMergeUtils;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.freight.api.RemoteFreightService;
import com.ruoyi.freight.api.domain.AeProductFreight;
import com.ruoyi.gather.api.domain.*;
import com.ruoyi.gather.api.domain.dto.ComputeFreightDto;
import com.ruoyi.gather.api.domain.vo.ErpCollectProductSkuVo;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysOss;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.domain.dto.OssUrlDto;
import com.ruoyi.system.api.domain.vo.SysOssVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.http.entity.ContentType;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 采集商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）Service业务层处理
 *
 * @author erp
 * @date 2023-03-07
 */
@RequiredArgsConstructor
@Service
public class ErpCollectProductServiceImpl implements IErpCollectProductService {
    private final ErpCollectProductMapper baseMapper;
    private final ErpPublicProductMapper erpPublicProductMapper;
    private final ErpCollectProductCategoryMapper collectProductCategoryMapper;
    private final ErpCollectProductUploadTestTaskMapper erpCollectProductUploadTestTaskMapper;
    private final ErpCollectProductSkuMapper erpCollectProductSkuMapper;
    private final ErpCollectProductExpandMapper erpCollectProductExpandMapper;
    private final IErpProductBrandService iErpProductBrandService;
    private final ErpCollectProductOptimizeTaskMapper optimizeTaskMapper;
    private final IErpCollectProductTranslateTaskService iErpCollectProductTranslateTaskService;
    private final ErpCollectProductOptimizeMapper collectProductOptimizeMapper;
    private final ErpProductUnifiedTakedownMapper erpProductUnifiedTakedownMapper;
    private final ErpSellerProductMapper erpSellerProductMapper;
    private final ErpSellerProductSkuMapper erpSellerProductSkuMapper;
    private final ErpSellerProductExpandMapper erpSellerProductExpandMapper;
    private final ErpSellerStoreProductMapper erpSellerStoreProductMapper;
    private final ErpSellerStoreProductExpandMapper erpSellerStoreProductExpandMapper;
    private final IErpCollectProductPublishTaskService iErpCollectProductPublishTaskService;
    private final IErpPythonMethodCallService iErpPythonMethodCallService;
    private final ErpCollectProductPublishTaskMapper collectProductPublishTaskMapper;
    private final ErpSellerCollectProductExpandMapper erpSellerCollectProductExpandMapper;
    private final IErpCollectProductSkuPriceService iErpCollectProductSkuPriceService;
    private final IErpSellerProductService iErpSellerProductService;
    private final ErpSellerCollectProductMapper erpSellerCollectProductMapper;
    private final ErpSellerCollectProductSkuMapper erpSellerCollectProductSkuMapper;
    private final IErpCollectProductCategoryService erpCollectProductCategoryService;
    private final AliexpressCategoryService aliexpressCategoryService;
    private final ErpProductAtlasMapper erpProductAtlasMapper;
    private final ErpSellerReplaceImageRecordMapper sellerReplaceImageRecordMapper;

    @Resource
    RestTemplate restTemplate;
    @Resource
    UrlConfig urlConfig;
    @Resource
    RemoteUserService remoteUserService;
    @Resource
    RemoteFileService remoteFileService;
    @Resource
    RemoteAeProductService remoteAeProductService;
    @Resource
    RemoteFreightService remoteFreightService;

    /**
     * 查询采集商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）列表
     * type: 0、1、2 0：公共采集列表 1：公共产品库 2：图片优化
     * TODO 删除打印
     */

    @Override
    public TableDataInfo<ErpCollectProductVo> queryPageList(ErpCollectProductBo bo, PageQuery pageQuery) {
        System.out.println("----0-进入方法" + new Date());
        LambdaQueryWrapper<ErpCollectProduct> lqw = buildQueryWrapper(bo);
        // 设置查询的字段
        List<SFunction<ErpCollectProduct, ?>> columns = new ArrayList<>();
        columns.add(ErpCollectProduct::getId);
        columns.add(ErpCollectProduct::getSubject);
        columns.add(ErpCollectProduct::getImageURLs);
        columns.add(ErpCollectProduct::getWhite);
        columns.add(ErpCollectProduct::getCategoryId);
        columns.add(ErpCollectProduct::getCollectUrl);
        columns.add(ErpCollectProduct::getProductPrice);
        columns.add(ErpCollectProduct::getDelFlag);
        columns.add(ErpCollectProduct::getCollectUserId);
        columns.add(ErpCollectProduct::getCreateTime);
        columns.add(ErpCollectProduct::getMarketing);
        lqw.select(columns);
        System.out.println("----1-开始查询" + new Date());
        Page<ErpCollectProductVo> result = new Page<ErpCollectProductVo>();
        if (bo.getType() != null && bo.getType().equals(1))
            result = erpPublicProductMapper.selectVoPage(pageQuery.build(), lqw);
        else
            result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        System.out.println("----1-查询结束" + new Date());

        System.out.println("----2-开始循环" + new Date());

        result.getRecords().forEach(vo -> {

            if (bo.getType().equals(0)) {
                Long categoryId = vo.getCategoryId();
                if (categoryId != null) {
                    ErpCollectProductCategory category = collectProductCategoryMapper.selectById(categoryId);
                    if (category != null)
                        vo.setCategoryName(category.getName());
                }
                // 查找测试时间
                ErpCollectProductUploadTestTask task = erpCollectProductUploadTestTaskMapper
                        .selectOne(new LambdaQueryWrapper<ErpCollectProductUploadTestTask>()
                                .eq(ErpCollectProductUploadTestTask::getCollectProductId, vo.getId())
                                .orderByDesc(ErpCollectProductUploadTestTask::getAddTime).last("limit 1"));

                if (ObjectUtils.isNotEmpty(task)) {
                    if (task.getTestTime() != null) {
                        String testTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(task.getTestTime());
                        vo.setTestTime(testTime);
                    }
                    if (task.getAddTime() != null) {
                        String addTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(task.getAddTime());
                        vo.setAddTime(addTime);
                    }
                }
            }

            if (bo.getType().equals(1)) {
                // 获取sku
                LambdaQueryWrapper<ErpCollectProductSku> skulqw = new LambdaQueryWrapper<ErpCollectProductSku>();

                List<SFunction<ErpCollectProductSku, ?>> skucolumns = new ArrayList<>();
                skucolumns.add(ErpCollectProductSku::getId);
                skucolumns.add(ErpCollectProductSku::getSkuImage);

                skulqw.select(skucolumns);
                skulqw.eq(ErpCollectProductSku::getCollectProductId, vo.getId());
                List<ErpCollectProductSkuVo> productVoSkus = erpCollectProductSkuMapper.selectVoList(skulqw);
                vo.setSkuList(productVoSkus);
            }

            LambdaQueryWrapper<ErpCollectProductExpand> expandLqw = new LambdaQueryWrapper<ErpCollectProductExpand>();

            List<SFunction<ErpCollectProductExpand, ?>> expandcolumns = new ArrayList<>();
            expandcolumns.add(ErpCollectProductExpand::getId);
            expandcolumns.add(ErpCollectProductExpand::getProductStatus);
            expandcolumns.add(ErpCollectProductExpand::getEditStatus);
            expandcolumns.add(ErpCollectProductExpand::getIsOptimize);
            expandcolumns.add(ErpCollectProductExpand::getIsFreight);
            expandcolumns.add(ErpCollectProductExpand::getIsTranslate);
            expandcolumns.add(ErpCollectProductExpand::getIsUploadTest);
            expandcolumns.add(ErpCollectProductExpand::getBrandId);
            expandcolumns.add(ErpCollectProductExpand::getClassifyLabel);
            expandcolumns.add(ErpCollectProductExpand::getIsAutoOptimize);
            expandcolumns.add(ErpCollectProductExpand::getAutoOptimizeRemark);

            expandLqw.select(expandcolumns);

            expandLqw.eq(ErpCollectProductExpand::getCollectProductId, vo.getId());
            // 获取产品扩展表
            ErpCollectProductExpandVo collectProductExpandVo = erpCollectProductExpandMapper.selectVoOne(expandLqw);

            // 查看品牌名字
            Long brandId = collectProductExpandVo.getBrandId();
            if (brandId != null) {
                ErpProductBrandVo brandVo = iErpProductBrandService.queryById(brandId);
                collectProductExpandVo.setBrandName(brandVo.getBrandName());
            }
            vo.setExpand(collectProductExpandVo);

            R<Object> sysUserInfo = remoteUserService.selectUserById(vo.getCollectUserId());
            String toJSONString = JSONObject.toJSONString(sysUserInfo.getData());
            SysUser sysUser = JSONObject.parseObject(toJSONString, SysUser.class);
            vo.setCollectUserName(sysUser == null ? "" : sysUser.getNickName());

            if (bo.getType().equals(2)) {
                // 获取自动优化状态
                ErpCollectProductOptimizeTask optimizeTask = optimizeTaskMapper
                        .selectOne(new LambdaQueryWrapper<ErpCollectProductOptimizeTask>()
                                .eq(ErpCollectProductOptimizeTask::getCollectProductId, vo.getId()).last("limit 1"));
                vo.setOptimizeTask(optimizeTask);
            }
        });
        System.out.println("----2-结束循环" + new Date());

        return TableDataInfo.build(result);
    }

    @Override
    public ErpCollectProductVo queryById(Long id) {
        ErpCollectProductVo erpCollectProductVo = baseMapper.selectVoById(id);

        // 获取sku
        List<ErpCollectProductSkuVo> productVoSkus = erpCollectProductSkuMapper.selectVoList(
                new LambdaQueryWrapper<ErpCollectProductSku>()
                        .eq(ErpCollectProductSku::getCollectProductId, id)
        );
        erpCollectProductVo.setSkuList(productVoSkus);

        // 获取产品扩展表
        ErpCollectProductExpandVo collectProductExpandVo = erpCollectProductExpandMapper.selectVoOne(
                new LambdaQueryWrapper<ErpCollectProductExpand>().eq(ErpCollectProductExpand::getCollectProductId, id));
        erpCollectProductVo.setExpand(collectProductExpandVo);

        return erpCollectProductVo;
    }

    @Override
    public Boolean insertByBo(ErpCollectProductBo bo) {
        ErpCollectProduct add = BeanUtil.toBean(bo, ErpCollectProduct.class);
        validEntityBeforeSave(add);

        add.setCollectUserId(SecurityUtils.getUserId());
        add.setRevision(CommonUtils.getRevision(null));
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());

            // 获取sku的信息
            List<ErpCollectProductSku> skuList = bo.getSkuList();
            // 查看是否有新增的
            skuList.stream().filter(sku -> StringUtils.isEmpty(sku.getSkuCode())).forEach(sku -> {
                sku.setSkuCode(CommonUtils.getSkuCode());
                sku.setCollectProductId(add.getId());
            });
            skuList.forEach(sku -> {
                // 判断sku是否存在
                LambdaQueryWrapper<ErpCollectProductSku> lqwSku = Wrappers.lambdaQuery();
                lqwSku.eq(ErpCollectProductSku::getSkuCode, sku.getSkuCode());
                lqwSku.eq(ErpCollectProductSku::getDelFlag, "0");
                lqwSku.last("limit 1");
                ErpCollectProductSku selectOne = erpCollectProductSkuMapper.selectOne(lqwSku);
                if (selectOne != null)
                    throw new RuntimeException("skucode重复，重复的商品id为：" + selectOne.getCollectProductId());
            });
            // 保存
            erpCollectProductSkuMapper.insertBatch(skuList);

            // 修改扩展表
            ErpCollectProductExpand expand = bo.getExpand();
            expand.setEditStatus(1);
            expand.setCollectProductId(add.getId());
            erpCollectProductExpandMapper.insert(expand);

        }
        return flag;
    }

    @Override
    public Boolean staging(ErpCollectProductBo bo) {
        boolean bool = true;
        if (bo.getId() == null) { // 新增暂存
            ErpCollectProduct add = BeanUtil.toBean(bo, ErpCollectProduct.class);
            validEntityBeforeSave(add);

            add.setCollectUserId(SecurityUtils.getUserId());
            add.setRevision(CommonUtils.getRevision(null));
            bool = baseMapper.insert(add) > 0;
            if (bool) {
                bo.setId(add.getId());

                // 获取sku的信息
                List<ErpCollectProductSku> skuList = bo.getSkuList();
                // 查看是否有新增的
                skuList.stream().filter(sku -> StringUtils.isEmpty(sku.getSkuCode())).forEach(sku -> {
                    sku.setSkuCode(CommonUtils.getSkuCode());
                    sku.setCollectProductId(add.getId());
                });
                skuList.forEach(sku -> {
                    // 判断sku是否存在
                    LambdaQueryWrapper<ErpCollectProductSku> lqwSku = Wrappers.lambdaQuery();
                    lqwSku.eq(ErpCollectProductSku::getSkuCode, sku.getSkuCode());
                    lqwSku.eq(ErpCollectProductSku::getDelFlag, "0");
                    lqwSku.last("limit 1");
                    ErpCollectProductSku selectOne = erpCollectProductSkuMapper.selectOne(lqwSku);
                    if (selectOne != null)
                        throw new RuntimeException("skucode重复，重复的商品id为：" + selectOne.getCollectProductId());
                });
                // 保存
                erpCollectProductSkuMapper.insertBatch(skuList);

                // 修改扩展表
                ErpCollectProductExpand expand = bo.getExpand();
                expand.setEditStatus(0); // 未编辑成功状态
                expand.setCollectProductId(add.getId());
                erpCollectProductExpandMapper.insert(expand);

            }
        } else { // 修改暂存
            // 获取数据库中的信息
            ErpCollectProduct collectProduct = baseMapper.selectById(bo.getId());
            // 判断revision
            if (bo.getRevision() != null && !bo.getRevision().equals(collectProduct.getRevision()))
                return false;

            ErpCollectProduct update = BeanUtil.toBean(bo, ErpCollectProduct.class);
            update.setRevision(CommonUtils.getRevision(collectProduct.getRevision()));

            validEntityBeforeSave(update);
            bool = baseMapper.updateById(update) > 0;

            // sku模块，后保存
            if (bool) {
                // 先删除
                erpCollectProductSkuMapper.deleteByCollectId(bo.getId());
                // 获取sku的信息
                List<ErpCollectProductSku> skuList = bo.getSkuList();
                // 查看是否有新增的
                skuList.stream().filter(sku -> StringUtils.isEmpty(sku.getSkuCode())).forEach(sku -> {
                    sku.setSkuCode(CommonUtils.getSkuCode());
                    sku.setCollectProductId(update.getId());
                });
                skuList.forEach(sku -> {
                    // 判断sku是否存在
                    LambdaQueryWrapper<ErpCollectProductSku> lqwSku = Wrappers.lambdaQuery();
                    lqwSku.eq(ErpCollectProductSku::getSkuCode, sku.getSkuCode());
                    lqwSku.eq(ErpCollectProductSku::getDelFlag, "0");
                    lqwSku.last("limit 1");
                    ErpCollectProductSku selectOne = erpCollectProductSkuMapper.selectOne(lqwSku);
                    if (selectOne != null)
                        throw new RuntimeException("skucode重复，重复的商品id为：" + selectOne.getCollectProductId());
                });
                // 保存
                erpCollectProductSkuMapper.insertBatch(skuList);

                // 修改扩展表
                ErpCollectProductExpand expand = bo.getExpand();
                LambdaUpdateWrapper<ErpCollectProductExpand> luw = new LambdaUpdateWrapper<>();
                luw.set(expand.getBrandId() == null, ErpCollectProductExpand::getBrandId, null);
                luw.eq(ErpCollectProductExpand::getId, expand.getId());

                // 判断是否修改了商品模板
                Integer templateId = expand.getTemplateId();
                if (ObjectUtils.isNotEmpty(templateId)) {
                    ErpCollectProductExpand expandSel = erpCollectProductExpandMapper
                            .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                                    .eq(ErpCollectProductExpand::getCollectProductId, collectProduct.getId()));
                    if (ObjectUtils.isNotEmpty(expandSel.getTemplateId())) {
                        if (templateId != expandSel.getTemplateId()) {
                            expand.setIsUpdateTemplate(1);
                            System.out.println("修改了商品模板");
                        }
                    }
                }

                erpCollectProductExpandMapper.update(expand, luw);
                erpCollectProductExpandMapper.updateById(expand);

                // 获取编辑状态
                Integer editStatus = expand.getEditStatus();
                if (editStatus.equals(1)) {
                    //TODO 运费相关 改造为内部Api调用
                    //重新运费试算
//                    erpCollectProductFreightTaskService.refresh(bo.getId(), 1);
                    // 重新翻译
                    iErpCollectProductTranslateTaskService.refresh(bo.getId(), 1);
                }
            }
        }
        return bool;
    }

    @Override
    public Boolean updateByBo(ErpCollectProductBo bo) {
// 获取数据库中的信息
        ErpCollectProduct collectProduct = baseMapper.selectById(bo.getId());
        // 判断revision
//		if (bo.getRevision() != null && !bo.getRevision().equals(collectProduct.getRevision()))
//			return false;

        // 去重图片，防止采集重复的图片在优化时被重复分配
        // 去重详情图
        List<String> detailImgs = Arrays.asList(bo.getDetailImg().split(";"));
        List<String> setDetailImgs = detailImgs.stream().distinct().collect(Collectors.toList());
        String detailImgString = String.join(";", setDetailImgs);
        bo.setDetailImg(detailImgString);
        // 去重轮播图
        List<String> imgImgs = Arrays.asList(bo.getImageURLs().split(";"));
        List<String> setImgs = imgImgs.stream().distinct().collect(Collectors.toList());
        String imgString = String.join(";", setImgs);
        bo.setImageURLs(imgString);

        ErpCollectProduct update = BeanUtil.toBean(bo, ErpCollectProduct.class);
        update.setRevision(CommonUtils.getRevision(collectProduct.getRevision()));
        validEntityBeforeSave(update);
        update.setOperateType(3); // 设置商品为采集已编辑
        boolean bool = baseMapper.updateById(update) > 0;

        // sku模块，后保存
        if (bool) {
            // 先删除
            erpCollectProductSkuMapper.deleteByCollectId(bo.getId());
            // 获取sku的信息
            List<ErpCollectProductSku> skuList = bo.getSkuList();
            // 查看是否有新增的
            skuList.stream().filter(sku -> StringUtils.isEmpty(sku.getSkuCode())).forEach(sku -> {
                sku.setSkuCode(CommonUtils.getSkuCode());
                sku.setCollectProductId(update.getId());
            });
            skuList.forEach(sku -> {
//                sku.setId(null);
                // 判断sku是否存在
                LambdaQueryWrapper<ErpCollectProductSku> lqwSku = Wrappers.lambdaQuery();
                lqwSku.eq(ErpCollectProductSku::getSkuCode, sku.getSkuCode());
                lqwSku.eq(ErpCollectProductSku::getDelFlag, "0");
                lqwSku.last("limit 1");
                ErpCollectProductSku selectOne = erpCollectProductSkuMapper.selectOne(lqwSku);
                if (selectOne != null)
                    throw new RuntimeException("skucode重复，重复的商品id为：" + selectOne.getCollectProductId());
            });
            // 保存
            erpCollectProductSkuMapper.insertOrUpdateBatch(skuList);

            // 修改扩展表
            ErpCollectProductExpand expand = bo.getExpand();
            expand.setEditStatus(bo.getExpand().getEditStatus());
            LambdaUpdateWrapper<ErpCollectProductExpand> luw = new LambdaUpdateWrapper<>();
            luw.set(expand.getBrandId() == null, ErpCollectProductExpand::getBrandId, null);
            luw.eq(ErpCollectProductExpand::getId, expand.getId());
            luw.set(expand.getClassifyLabel() != null, ErpCollectProductExpand::getClassifyLabel, expand.getClassifyLabel());
            erpCollectProductExpandMapper.update(expand, luw);

        }

        //TODO OSS相关 待测试
        updateProductUrl(collectProduct.getId());
        // 添加到翻译
        //TODO 运费相关 改造为内部Api调用
//        erpCollectProductFreightTaskService.refresh(collectProduct.getId(), 1);
        iErpCollectProductTranslateTaskService.refresh(collectProduct.getId(), 1);
        ErpCollectProductExpand erpCollectProductExpand = erpCollectProductExpandMapper
                .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                        .eq(ErpCollectProductExpand::getCollectProductId, bo.getId()));
        if (!erpCollectProductExpand.getIsOptimize().equals(2))
            erpCollectProductExpand.setIsOptimize(0);
        if (erpCollectProductExpand.getIsAutoOptimize() != 1) {
            erpCollectProductExpand.setIsAutoOptimize(1);
            erpCollectProductExpand.setAutoOptimizeRemark("商品编辑完成");
        }
        erpCollectProductExpandMapper.updateById(erpCollectProductExpand);
        return bool;
    }

    @Override
    public R<String> deleteWithValidByIds(List<Long> ids, boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }

        // 获取商品的信息，判断上架的状态
        LambdaQueryWrapper<ErpCollectProductExpand> lqw = Wrappers.lambdaQuery();
        lqw.in(ErpCollectProductExpand::getCollectProductId, ids);
        lqw.eq(ErpCollectProductExpand::getProductStatus, 1); // 上架
        List<ErpCollectProductExpand> selectList = erpCollectProductExpandMapper.selectList(lqw);
        if (selectList.size() > 0) {
            return R.fail("删除失败，请先下架商品!");
        }

        // 删除修改为下架
//		baseMapper.deleteBatchIds(ids);

        LambdaUpdateWrapper<ErpCollectProductExpand> luw = Wrappers.lambdaUpdate();
        luw.set(ErpCollectProductExpand::getProductStatus, 0); // 下架
        luw.in(ErpCollectProductExpand::getCollectProductId, ids);
        erpCollectProductExpandMapper.update(null, luw);

        LambdaUpdateWrapper<ErpCollectProduct> luw1 = Wrappers.lambdaUpdate();
        luw1.set(ErpCollectProduct::getDelFlag, 2); // 已删除
        luw1.in(ErpCollectProduct::getId, ids);
        baseMapper.update(null, luw1);

//        erpCollectProductSkuMapper.delete(
//                new LambdaQueryWrapper<ErpCollectProductSku>().in(ErpCollectProductSku::getCollectProductId, ids));
//        erpCollectProductExpandMapper.delete(new LambdaQueryWrapper<ErpCollectProductExpand>()
//                .in(ErpCollectProductExpand::getCollectProductId, ids));
        return R.ok("删除成功");
    }

    @Override
    public Boolean copyProd(Long productId) {

        // 获取商品
        ErpCollectProduct collectProduct = baseMapper.selectById(productId);

        // 获取扩展
        ErpCollectProductExpand expand = erpCollectProductExpandMapper
                .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                        .eq(ErpCollectProductExpand::getCollectProductId, productId).last(" limit 1 "));

        List<ErpCollectProductSku> skuList = erpCollectProductSkuMapper
                .selectList(new LambdaQueryWrapper<ErpCollectProductSku>().eq(ErpCollectProductSku::getCollectProductId,
                        productId));

        // 复制
        collectProduct.setId(null);
        baseMapper.insert(collectProduct);

        expand.setId(null);
        expand.setCollectProductId(collectProduct.getId());
        erpCollectProductExpandMapper.insert(expand);

        for (ErpCollectProductSku erpCollectProductSku : skuList) {
            erpCollectProductSku.setId(null);
            erpCollectProductSku.setCollectProductId(collectProduct.getId());
            erpCollectProductSku.setSkuCode(CommonUtils.getSkuCode()); // 设置新的skucode
            erpCollectProductSkuMapper.insert(erpCollectProductSku);
        }

        // 判断是否已经优化，若已经优化，需要把元素图也辅助一下
        Integer isOptimize = expand.getIsOptimize();
        if (isOptimize.equals(1)) {
            List<ErpCollectProductOptimize> optimizeList = collectProductOptimizeMapper
                    .selectList(new LambdaQueryWrapper<ErpCollectProductOptimize>()
                            .eq(ErpCollectProductOptimize::getCollectProductId, productId));

            optimizeList.forEach(optimize -> {
                optimize.setId(null);
                optimize.setCollectProductId(collectProduct.getId());
                collectProductOptimizeMapper.insert(optimize);
            });
        }

        return true;
    }

    @Override
    public R<Object> updateStatus(Long productId, Integer productStatus) {
        // 获取商品扩展类
        ErpCollectProductExpand expand = erpCollectProductExpandMapper
                .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                        .eq(ErpCollectProductExpand::getCollectProductId, productId));
        if (productStatus.equals(1)) { // 上架商家需要先判断是否已优化
            Integer isOptimize = expand.getIsOptimize();
//            if (isOptimize.equals(0))
//                return R.fail("商品未优化");
            if (expand.getIsUploadTest() != 2) {
                return R.fail("商品未进行上架测试");
            }
            ErpProductUnifiedTakedown erpProductUnifiedTakedown = erpProductUnifiedTakedownMapper
                    .selectOne(new LambdaQueryWrapper<ErpProductUnifiedTakedown>()
                            .eq(ErpProductUnifiedTakedown::getCollectProductId, productId)
                            .eq(ErpProductUnifiedTakedown::getIsEffective, 1).last("limit 1"));
            if (erpProductUnifiedTakedown != null) {
                return R.fail("该商品目前为系统下架状态，原因为：" + erpProductUnifiedTakedown.getTakedownReason() + "，是否确认该问题已修复？");
            }
            // 修改商品的sku和区域定价
            updateSkuProperty(productId);
        }
        // 修改
        LambdaUpdateWrapper<ErpCollectProductExpand> luw = new LambdaUpdateWrapper<ErpCollectProductExpand>();
        luw.eq(ErpCollectProductExpand::getCollectProductId, productId);
        luw.set(ErpCollectProductExpand::getProductStatus, productStatus);
        erpCollectProductExpandMapper.update(null, luw);

        return R.ok();
    }

    @Override
    @Transactional
    public void updateSkuProperty(Long productId) {

        // 获取商品
        ErpCollectProduct product = baseMapper.selectById(productId);
        Long categoryId = product.getCategoryId();

        // 根据类目获取所需的sku属性
        Map<Integer, List<Integer>> skuPropertyMap = aliexpressCategoryService.getSkuPropertyById(categoryId);

        // 获取商品爬取的sku属性
        ErpCollectProductExpand expand = erpCollectProductExpandMapper
                .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                        .eq(ErpCollectProductExpand::getCollectProductId, productId).last(" limit 1 "));
        String skuProperty = expand.getSkuProperty();
        List<Dict> skuPropertyList = JsonUtils.parseArrayMap(skuProperty);

        // 替换值map
        Map<Integer, Integer> thNameMap = new HashMap<>();
        Map<Integer, Integer> thValueMap = new HashMap<>();
        List<Integer> nameIdList = new ArrayList<>(skuPropertyMap.keySet());
        if (skuPropertyMap.size() < skuPropertyList.size()) {
            throw new RuntimeException(
                    "速卖通类目规格为：" + skuPropertyMap.size() + "个，erp商品规格个数为：" + skuPropertyList.size() + "个，请手动合并规格。");
        }
        for (int i = 0; i < skuPropertyList.size(); i++) {
            Dict dict = skuPropertyList.get(i);
            Integer oldNameId = (Integer) dict.get("value");
            String name = (String) dict.get("name");

            // 替换PropertyValue
            Integer nameId = nameIdList.get(i);
            dict.set("value", nameId);
            thNameMap.put(oldNameId, nameId);
            List<Integer> valueIdList = skuPropertyMap.get(nameId);

            // 获取值Value
            List<HashMap<String, Object>> valueList = (List<HashMap<String, Object>>) dict.get("list");
            if (valueIdList.size() < valueList.size())
                throw new RuntimeException(
                        "属性：" + name + "在速卖通可选值为" + valueIdList.size() + "个，当前个数为" + valueList.size() + "个，超出备选个数！");
            for (int j = 0; j < valueList.size(); j++) {
                HashMap<String, Object> valueMap = valueList.get(j);
                Integer oldValueId = (Integer) valueMap.get("value");
                // 替换
                Integer valueId = valueIdList.get(j);
                valueMap.put("value", valueId);
                thValueMap.put(oldValueId, valueId);
            }
        }
        skuProperty = JsonUtils.toJsonString(skuPropertyList);
        expand.setSkuProperty(skuProperty);

        // 获取sku
        List<ErpCollectProductSku> skuList = erpCollectProductSkuMapper
                .selectList(new LambdaQueryWrapper<ErpCollectProductSku>().eq(ErpCollectProductSku::getCollectProductId,
                        productId));
        Map<String, String> thPopertyIdsMap = new HashMap<>();
        for (ErpCollectProductSku erpCollectProductSku : skuList) {
            String skuPropertyIds = erpCollectProductSku.getSkuPropertyIds();

            String skuPropertyIdsNew = "";
            // 切割字符串，替换
            String[] split = skuPropertyIds.split(";");
            for (String s : split) {
                String[] split2 = s.split(":");
                String nameId = split2[0];
                String valueId = split2[1];
                // 替换
                Integer newNameId = thNameMap.get(Integer.valueOf(nameId));
                Integer newValueIdId = thValueMap.get(Integer.valueOf(valueId));

                skuPropertyIdsNew += newNameId + ":" + newValueIdId + ";";
            }

            // 切割掉最后的","
            skuPropertyIdsNew = skuPropertyIdsNew.substring(0, skuPropertyIdsNew.lastIndexOf(";"));
            erpCollectProductSku.setSkuPropertyIds(skuPropertyIdsNew);

            thPopertyIdsMap.put(skuPropertyIds, skuPropertyIdsNew);
        }
        String freightMap = expand.getFreightMap();
        List<Dict> freightMapList = JsonUtils.parseArrayMap(freightMap);
        try {
            // 最后替换运费试算
            for (Dict dict : freightMapList) {
                Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                Map<String, Double> absoluteQuoteMapNew = new HashMap<>();
                for (String key : absoluteQuoteMap.keySet()) {
                    String newKey = thPopertyIdsMap.get(key);
                    Double obj = Double.valueOf(absoluteQuoteMap.get(key).toString());
                    if (StringUtils.isNotEmpty(newKey))
                        absoluteQuoteMapNew.put(newKey, obj);
                    else
                        absoluteQuoteMapNew.put(key, obj);
                }
                dict.put("absoluteQuoteMap", absoluteQuoteMapNew);
            }

            // 获取完成的运费试算
            freightMap = JsonUtils.toJsonString(freightMapList);
            expand.setFreightMap(freightMap);

        } catch (Exception e) {
            throw new RuntimeException("商品sku个数变动，请重新运费试算");
        }

        Map<String, BigDecimal> skuMap = new HashMap<>();
        if (expand.getClassifyLabel().contains("1719179918137212929")) {
            skuList.forEach(sku -> skuMap.put(sku.getSkuPropertyIds(), new BigDecimal(sku.getSkuPrice())));
        } else {
            skuList.forEach(sku -> skuMap.put(sku.getSkuPropertyIds(),
                    new BigDecimal(sku.getSkuPrice()).multiply(new BigDecimal(1.1))));
        }

        // 创建skuprice的map
//		Map<String, Map<String, BigDecimal>> skuPriceMap = new HashMap<>();
//
//		Map<String, BigDecimal> skuPriceMinMap = new HashedMap<>();

        Double min = null;
        Double max = null;

        // 获取运费，修改金额
        for (Dict dict : freightMapList) {
            Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
            String shiptoCountry = (String) dict.get("shiptoCountry");
            for (String key : absoluteQuoteMap.keySet()) {
                BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());

                // 添加sku价格
//				if (skuPriceMinMap.containsKey(key)) {
//					BigDecimal price = skuPriceMinMap.get(key);
//					if (price.compareTo(amount) == 1)
//						skuPriceMinMap.put(key, amount);
//				} else {
//					skuPriceMinMap.put(key, amount);
//				}

                // 获取sku
                BigDecimal skuPrice = skuMap.get(key);

                // 计算最终价格
                amount = skuPrice.add(amount).setScale(2, BigDecimal.ROUND_HALF_UP);
                Double res = amount.doubleValue();
                absoluteQuoteMap.put(key, res);
                if (shiptoCountry.equals("US")) {
                    if (min == null || res < min)
                        min = res;
                    if (max == null || res > max)
                        max = res;
                }

//				if (skuPriceMap.containsKey(key)) {
//					Map<String, BigDecimal> map1 = skuPriceMap.get(key);
//					map1.put(dict.getStr("shiptoCountry"), amount);
//				} else {
//					Map<String, BigDecimal> map1 = new HashMap<String, BigDecimal>();
//					map1.put(dict.getStr("shiptoCountry"), amount);
//					skuPriceMap.put(key, map1);
//				}
            }
        }

        // 获取完成的区域定价
        String absoluteQuoteMap = JsonUtils.toJsonString(freightMapList);
        expand.setAbsoluteQuoteMap(absoluteQuoteMap);

        // 修改商品的价格
        product.setId(productId);
        product.setProductPrice(min.equals(max) ? min + "" : min + "-" + max);
        baseMapper.updateById(product);

        // 保存
        erpCollectProductSkuMapper.updateBatchById(skuList);
        erpCollectProductExpandMapper.updateById(expand);
    }

    @Override
    @Transactional
    public R<Object> updateSkuPropertyByProductA(ComputeFreightDto dto) {
        // 获取商品
        ErpCollectProduct product = JSONObject.parseObject(dto.getProduct().toString(), ErpCollectProduct.class);
        // 获取扩展信息
        ErpCollectProductExpand expand = JSONObject.parseObject(dto.getProductExpand().toString(), ErpCollectProductExpand.class);
        //获取sku信息
        List<ErpCollectProductSku> skuList = JSONArray.parseArray(dto.getProductSkuList().toJSONString(), ErpCollectProductSku.class);


        // 获取商品
        Long categoryId = product.getCategoryId();

        // 根据类目获取所需的sku属性
        Map<Integer, List<Integer>> skuPropertyMap = aliexpressCategoryService.getSkuPropertyById(categoryId);
        System.out.println(" skuPropertyMap :" + JsonUtils.toJsonString(skuPropertyMap));

        String skuProperty = expand.getSkuProperty();
        List<Dict> skuPropertyList = JsonUtils.parseArrayMap(skuProperty);

        // 替换值map
        Map<Integer, Integer> thNameMap = new HashMap<>();
        Map<Integer, Integer> thValueMap = new HashMap<>();
        List<Integer> nameIdList = new ArrayList<>(skuPropertyMap.keySet());
        if (skuPropertyMap.size() < skuPropertyList.size()) {
            throw new RuntimeException(
                    "速卖通类目规格为：" + skuPropertyMap.size() + "个，erp商品规格个数为：" + skuPropertyList.size() + "个，请手动合并规格。");
        }
        for (int i = 0; i < skuPropertyList.size(); i++) {
            Dict dict = skuPropertyList.get(i);
            Integer oldNameId = null;
            try{
                oldNameId = (Integer) dict.get("value");
            }catch (ClassCastException e){
                //类型转换异常
                String oldNameIdString = (String) dict.get("value");
                oldNameId = Integer.valueOf(oldNameIdString);
            }
            String name = (String) dict.get("name");

            // 替换PropertyValue
            Integer nameId = nameIdList.get(i);
            dict.set("value", nameId);
            thNameMap.put(oldNameId, nameId);
            List<Integer> valueIdList = skuPropertyMap.get(nameId);

            // 获取值Value
            List<HashMap<String, Object>> valueList = (List<HashMap<String, Object>>) dict.get("list");
            if (valueIdList.size() < valueList.size())
                throw new RuntimeException(
                        "属性：" + name + "在速卖通可选值为" + valueIdList.size() + "个，当前个数为" + valueList.size() + "个，超出备选个数！");
            for (int j = 0; j < valueList.size(); j++) {
                HashMap<String, Object> valueMap = valueList.get(j);
                Integer oldValueId = null;
                try{
                    oldValueId = (Integer) valueMap.get("value");
                }catch (ClassCastException e){
                    //类型转换异常
                    String oldValueIdString = (String) valueMap.get("value");
                    oldValueId = Integer.valueOf(oldValueIdString);
                }

                // 替换
                Integer valueId = valueIdList.get(j);
                valueMap.put("value", valueId);
                thValueMap.put(oldValueId, valueId);
            }
        }
        skuProperty = JsonUtils.toJsonString(skuPropertyList);
        expand.setSkuProperty(skuProperty);

        Map<String, String> thPopertyIdsMap = new HashMap<>();
        for (ErpCollectProductSku erpCollectProductSku : skuList) {
            String skuPropertyIds = erpCollectProductSku.getSkuPropertyIds();

            String skuPropertyIdsNew = "";
            // 切割字符串，替换
            String[] split = skuPropertyIds.split(";");
            for (String s : split) {
                String[] split2 = s.split(":");
                String nameId = split2[0];
                String valueId = split2[1];
                // 替换
                Integer newNameId = thNameMap.get(Integer.valueOf(nameId));
                Integer newValueIdId = thValueMap.get(Integer.valueOf(valueId));

                skuPropertyIdsNew += newNameId + ":" + newValueIdId + ";";
            }

            // 切割掉最后的","
            skuPropertyIdsNew = skuPropertyIdsNew.substring(0, skuPropertyIdsNew.lastIndexOf(";"));
            erpCollectProductSku.setSkuPropertyIds(skuPropertyIdsNew);

            thPopertyIdsMap.put(skuPropertyIds, skuPropertyIdsNew);
        }
        String freightMap = expand.getFreightMap();
        List<Dict> freightMapList = JsonUtils.parseArrayMap(freightMap);
        try {
            // 最后替换运费试算
            for (Dict dict : freightMapList) {
                Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                Map<String, Double> absoluteQuoteMapNew = new HashMap<>();
                for (String key : absoluteQuoteMap.keySet()) {
                    String newKey = thPopertyIdsMap.get(key);
                    Double obj = Double.valueOf(absoluteQuoteMap.get(key).toString());
                    if (StringUtils.isNotEmpty(newKey))
                        absoluteQuoteMapNew.put(newKey, obj);
                    else
                        absoluteQuoteMapNew.put(key, obj);
                }
                dict.put("absoluteQuoteMap", absoluteQuoteMapNew);
            }

            // 获取完成的运费试算
            freightMap = JsonUtils.toJsonString(freightMapList);
            expand.setFreightMap(freightMap);

        } catch (Exception e) {
            throw new RuntimeException("商品sku个数变动，请重新运费试算");
        }

        Map<String, BigDecimal> skuMap = new HashMap<>();
//        if (expand.getClassifyLabel().contains("1719179918137212929")) {
//            skuList.forEach(sku -> skuMap.put(sku.getSkuPropertyIds(), new BigDecimal(sku.getSkuPrice())));
//        } else {
        skuList.forEach(sku -> skuMap.put(sku.getSkuPropertyIds(),
                new BigDecimal(sku.getSkuPrice()).multiply(new BigDecimal(1.1))));
//        }

        // 创建skuprice的map
//		Map<String, Map<String, BigDecimal>> skuPriceMap = new HashMap<>();
//
//		Map<String, BigDecimal> skuPriceMinMap = new HashedMap<>();

        Double min = null;
        Double max = null;

        // 获取运费，修改金额
        for (Dict dict : freightMapList) {
            Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
            String shiptoCountry = (String) dict.get("shiptoCountry");
            for (String key : absoluteQuoteMap.keySet()) {
                BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());

                // 添加sku价格
//				if (skuPriceMinMap.containsKey(key)) {
//					BigDecimal price = skuPriceMinMap.get(key);
//					if (price.compareTo(amount) == 1)
//						skuPriceMinMap.put(key, amount);
//				} else {
//					skuPriceMinMap.put(key, amount);
//				}

                // 获取sku
                BigDecimal skuPrice = skuMap.get(key);

                // 计算最终价格
                amount = skuPrice.add(amount).setScale(2, BigDecimal.ROUND_HALF_UP);
                Double res = amount.doubleValue();
                absoluteQuoteMap.put(key, res);
                if (shiptoCountry.equals("US")) {
                    if (min == null || res < min)
                        min = res;
                    if (max == null || res > max)
                        max = res;
                }

//				if (skuPriceMap.containsKey(key)) {
//					Map<String, BigDecimal> map1 = skuPriceMap.get(key);
//					map1.put(dict.getStr("shiptoCountry"), amount);
//				} else {
//					Map<String, BigDecimal> map1 = new HashMap<String, BigDecimal>();
//					map1.put(dict.getStr("shiptoCountry"), amount);
//					skuPriceMap.put(key, map1);
//				}
            }
        }

        // 获取完成的区域定价
        String absoluteQuoteMap = JsonUtils.toJsonString(freightMapList);
        expand.setAbsoluteQuoteMap(absoluteQuoteMap);

        // 修改商品的价格
        product.setProductPrice(min.equals(max) ? min + "" : min + "-" + max);

        // 保存
        dto.setProduct(JSONObject.parseObject(JSONObject.toJSONString(product)));
        dto.setProductExpand(JSONObject.parseObject(JSONObject.toJSONString(expand)));
        dto.setProductSkuList(JSONArray.parseArray(JSONObject.toJSONString(skuList)));

        return R.ok(dto);
    }

    @Override
    public R<Object> queryProductComputeFreight64() {
        List<ErpCollectProduct> erpCollectProducts = baseMapper.selectList();
        for (ErpCollectProduct product : erpCollectProducts) {
            ErpCollectProductExpand expand = erpCollectProductExpandMapper.selectByCollectProductId(product.getId());
            List<ErpCollectProductSku> list = erpCollectProductSkuMapper.selectList(
                    new LambdaQueryWrapper<ErpCollectProductSku>().eq(ErpCollectProductSku::getCollectProductId, product.getId()));

            ComputeFreightDto dto = new ComputeFreightDto();
            dto.setProduct(JSONObject.parseObject(JSONObject.toJSONString(product)));
            dto.setProductSkuList(JSONArray.parseArray(JSONObject.toJSONString(list)));
            dto.setProductExpand(JSONObject.parseObject(JSONObject.toJSONString(expand)));
            R<Object> objectRA = remoteFreightService.computeFreightWith64(dto);
            String returnStrA = JSONObject.toJSONString(objectRA.getData());
            ComputeFreightDto computeFreightDtoA = JSONObject.parseObject(returnStrA, ComputeFreightDto.class);
            System.out.println(computeFreightDtoA);

            ErpCollectProduct returnProductA = JSONObject.parseObject(computeFreightDtoA.getProduct().toString(), ErpCollectProduct.class);
            ErpCollectProductExpand returnProductExpandA = JSONObject.parseObject(computeFreightDtoA.getProductExpand().toString(), ErpCollectProductExpand.class);
            List<ErpCollectProductSku> returnProductSkuA = JSONArray.parseArray(computeFreightDtoA.getProductSkuList().toString(), ErpCollectProductSku.class);

            baseMapper.updateById(returnProductA);
            erpCollectProductExpandMapper.updateById(returnProductExpandA);
            for (ErpCollectProductSku sku : returnProductSkuA) {
                erpCollectProductSkuMapper.updateById(sku);
            }
        }
        return R.ok();

    }

    @Override
    public R<Object> queryCategoryBySubject(String subject) {
        // 根据标题获取类目
        Map<String, Object> map = new HashMap<>();
        map.put("title", subject);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://47.94.131.193:8000/product/getCidByTitle", map, String.class);
        String body = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        Integer code = jsonObject.getInteger("code");
        if (code == 200) {
            JSONArray dataArray = jsonObject.getJSONArray("data");
            if (dataArray.size() != 0) {
                Long id = dataArray.getJSONObject(0).getLong("id");
                return  R.ok(id);
            }else {
                return  R.fail("获取标题失败");
            }
        }else {
            return  R.fail("获取标题失败");
        }

    }

    @Override
    public R<Object> batchGrounding(String productIds, String type) {
        List<String> productIdList = ListUtil.toList(productIds.split(","));
        if (productIdList.size() == 1) {
            return oneGrounding(productIds, type);
        } else {
            return batchGrounding(productIdList, type);
        }
    }

    @Override
    public R<Object> soldOutCollectProduct(Long productIds, String type) {
        // 下架商品
        LambdaUpdateWrapper<ErpCollectProductExpand> luw = new LambdaUpdateWrapper<ErpCollectProductExpand>();
        luw.eq(ErpCollectProductExpand::getCollectProductId, productIds);
        luw.set(ErpCollectProductExpand::getProductStatus, 0);
        erpCollectProductExpandMapper.update(null, luw);

        // 分割字符串,查看选择
        List<String> typeList = ListUtil.toList(type.split(","));
        if (typeList.size() > 0) {

            Boolean soldOutFlag = typeList.stream().allMatch((typeStr) -> typeStr.equals("1"));
            // 选择了1
            int code = 0;
            if (soldOutFlag) {
                // 同步下架所有速卖通店铺该商品
                R<Object> soldOutProductObject = soldOutProductByCollectId(productIds);
                code = soldOutProductObject.getCode();
                if (code != 200) {
                    return R.fail(soldOutProductObject.getData());
                }
            }
            Boolean deleteFlag = typeList.stream().allMatch((typeStr) -> typeStr.equals("2"));
            // 选择了2
            if (deleteFlag) {
                // 同步下架所有速卖通店铺该商品
                R<Object> deleteProductObject = deleteProductByCollectId(productIds);
                code = deleteProductObject.getCode();
                if (code != 200) {
                    return R.fail(deleteProductObject.getData());
                }
            }

        }
        return R.ok("下架成功");
    }

    @Override
    public R<Object> batchSoldOutCollectProduct(String productIds, String type) {
        List<String> productIdList = ListUtil.toList(productIds.split(","));
        List<String> errorList = new ArrayList<>();
        List<String> successList = new ArrayList<>();
        for (String productId : productIdList) {
            R<Object> objectR = soldOutCollectProduct(Long.valueOf(productId), type);
            if (objectR.getCode() == 200) {
                successList.add(productId);
            } else {
                errorList.add(productId);
            }
        }
        if (errorList.size() > 0) {
            String res = "下架成功个数：" + (successList.size() - errorList.size()) + ", 失败个数：" + errorList.size() + " ,失败id为："
                    + errorList.toString();
            return R.fail(res);
        } else {
            return R.ok("下架成功个数：" + productIdList.size());
        }
    }

    // 同步下架所有速卖通店铺该商品
    public R<Object> soldOutProductByCollectId(Long collectProductId) {
        try {
            // 1、获取到公共产品库商品，执行操作为 ： 下架
            ErpCollectProductExpand collectProductExpand = erpCollectProductExpandMapper
                    .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                            .eq(ErpCollectProductExpand::getCollectProductId, collectProductId));
            if (collectProductExpand == null) {
                return R.fail("该商品不存在");
            }
            collectProductExpand.setProductStatus(0);
            erpCollectProductExpandMapper.updateById(collectProductExpand);
            // 2、获取到个人产品库商品，执行操作为 ： 删除
            List<ErpSellerProduct> erpSellerProductList = erpSellerProductMapper
                    .selectList(new LambdaQueryWrapper<ErpSellerProduct>().eq(ErpSellerProduct::getCollectProductId,
                            collectProductId));
            Long sellerProductId = null;
            ErpSellerProductExpand erpSellerProductExpand = new ErpSellerProductExpand();
            List<ErpSellerProductSku> sellerProductSkuList = new ArrayList<>();
            for (ErpSellerProduct sellerProduct : erpSellerProductList) {
                sellerProductId = sellerProduct.getId();
                // 删除sku表
                sellerProductSkuList = erpSellerProductSkuMapper
                        .selectList(new LambdaQueryWrapper<ErpSellerProductSku>()
                                .eq(ErpSellerProductSku::getSellerProductId, sellerProductId));
                erpSellerProductSkuMapper.deleteBatchIds(sellerProductSkuList);
                erpSellerProductMapper.deleteById(sellerProduct);

                // 删除延伸表
                erpSellerProductExpand = erpSellerProductExpandMapper
                        .selectOne(new LambdaQueryWrapper<ErpSellerProductExpand>()
                                .eq(ErpSellerProductExpand::getSellerProductId, sellerProductId));
                erpSellerProductExpandMapper.deleteById(erpSellerProductExpand);

            }

            // 3、获取到在线商品库商品，执行操作为 ： Erp内改变状态，速卖通下架+删除
            List<ErpSellerStoreProduct> erpSellerStoreProductList = erpSellerStoreProductMapper
                    .selectList(new LambdaQueryWrapper<ErpSellerStoreProduct>()
                            .eq(ErpSellerStoreProduct::getCollectProductId, collectProductId));
            Long sellerStoreProductId = null;
            ErpSellerStoreProductExpand erpSellerStoreProductExpand = new ErpSellerStoreProductExpand();
            List<ErpSellerStoreProductSku> sellerStoreProductSkuList = new ArrayList<>();
            for (ErpSellerStoreProduct sellerStoreProduct : erpSellerStoreProductList) {
                sellerStoreProductId = sellerStoreProduct.getId();
                // 修改状态
                erpSellerStoreProductExpand = erpSellerStoreProductExpandMapper
                        .selectOne(new LambdaQueryWrapper<ErpSellerStoreProductExpand>()
                                .eq(ErpSellerStoreProductExpand::getSellerStoreProductId, sellerStoreProductId));
                erpSellerStoreProductExpand.setProductStatusType("5");
                erpSellerStoreProductExpandMapper.updateById(erpSellerStoreProductExpand);
                // 7、下架产品Long sellerStoreProductIds, Long sellerId, Integer type
                if (sellerStoreProduct.getAeProductId() != null) {
                    // 8、删除产品
                    // 下架速卖通商品
                    //TODO Ae相关 内部调用 待测试
                    Map<String, Object> map = new HashMap<>();
                    map.put("aeProductIds", sellerStoreProduct.getAeProductId().toString());
                    map.put("storeId", sellerStoreProduct.getStoreId());
                    map.put("type", 0);
                    remoteAeProductService.productOfflineForUpdateTestInnerAuth(map);
//                    aeProductService.productOfflineForUpdateTest(sellerStoreProduct.getAeProductId().toString(),
//                            sellerStoreProduct.getStoreId(), 0);
                }

            }
        } catch (Exception e) {
            return R.fail("下架异常");
        }
        return R.ok("下架成功");
    }


    // 同步删除所有速卖通店铺该商品
    public R<Object> deleteProductByCollectId(Long collectProductId) {
        try {
            // 1、获取到公共产品库商品，执行操作为 ： 下架
            ErpCollectProductExpand collectProductExpand = erpCollectProductExpandMapper
                    .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                            .eq(ErpCollectProductExpand::getCollectProductId, collectProductId));
            if (collectProductExpand == null) {
                return R.fail("该商品不存在");
            }
            collectProductExpand.setProductStatus(0);
            erpCollectProductExpandMapper.updateById(collectProductExpand);
            // 2、获取到个人产品库商品，执行操作为 ： 删除
            List<ErpSellerProduct> erpSellerProductList = erpSellerProductMapper
                    .selectList(new LambdaQueryWrapper<ErpSellerProduct>().eq(ErpSellerProduct::getCollectProductId,
                            collectProductId));
            Long sellerProductId = null;
            ErpSellerProductExpand erpSellerProductExpand = new ErpSellerProductExpand();
            List<ErpSellerProductSku> sellerProductSkuList = new ArrayList<>();
            for (ErpSellerProduct sellerProduct : erpSellerProductList) {
                sellerProductId = sellerProduct.getId();
                // 删除sku表
                sellerProductSkuList = erpSellerProductSkuMapper
                        .selectList(new LambdaQueryWrapper<ErpSellerProductSku>()
                                .eq(ErpSellerProductSku::getSellerProductId, sellerProductId));
                erpSellerProductSkuMapper.deleteBatchIds(sellerProductSkuList);
                erpSellerProductMapper.deleteById(sellerProduct);

                // 删除延伸表
                erpSellerProductExpand = erpSellerProductExpandMapper
                        .selectOne(new LambdaQueryWrapper<ErpSellerProductExpand>()
                                .eq(ErpSellerProductExpand::getSellerProductId, sellerProductId));
                erpSellerProductExpandMapper.deleteById(erpSellerProductExpand);

            }

            // 3、获取到在线商品库商品，执行操作为 ： Erp内改变状态，速卖通下架+删除
            List<ErpSellerStoreProduct> erpSellerStoreProductList = erpSellerStoreProductMapper
                    .selectList(new LambdaQueryWrapper<ErpSellerStoreProduct>()
                            .eq(ErpSellerStoreProduct::getCollectProductId, collectProductId));
            Long sellerStoreProductId = null;
            ErpSellerStoreProductExpand erpSellerStoreProductExpand = new ErpSellerStoreProductExpand();
            List<ErpSellerStoreProductSku> sellerStoreProductSkuList = new ArrayList<>();
            for (ErpSellerStoreProduct sellerStoreProduct : erpSellerStoreProductList) {
                sellerStoreProductId = sellerStoreProduct.getId();
                // 修改状态
                erpSellerStoreProductExpand = erpSellerStoreProductExpandMapper
                        .selectOne(new LambdaQueryWrapper<ErpSellerStoreProductExpand>()
                                .eq(ErpSellerStoreProductExpand::getSellerStoreProductId, sellerStoreProductId));
                erpSellerStoreProductExpand.setProductStatusType("5");
                erpSellerStoreProductExpandMapper.updateById(erpSellerStoreProductExpand);
                // 7、下架产品Long sellerStoreProductIds, Long sellerId, Integer type
                if (sellerStoreProduct.getAeProductId() != null) {
                    // 8、删除产品
                    //TODO Ae相关 内部调用 待测试
//                    // 下架速卖通商品
                    Map<String, Object> map = new HashMap<>();
                    map.put("aeProductIds", sellerStoreProduct.getAeProductId().toString());
                    map.put("storeId", sellerStoreProduct.getStoreId());
                    map.put("type", 0);
                    remoteAeProductService.productOfflineForUpdateTestInnerAuth(map);
//                    // 删除速卖通商品
                    remoteAeProductService.deleteProductToAe(sellerStoreProduct.getAeProductId(), sellerStoreProduct.getStoreId());
                }

            }
        } catch (Exception e) {
            return R.fail("下架删除异常");
        }
        return R.ok("下架成功");
    }

    /**
     * 子 - 批量上架
     *
     * @param type
     * @return
     */
    public R<Object> batchGrounding(List<String> productIdList, String type) {
        List<Long> errorList = new ArrayList<Long>();
        for (String productStr : productIdList) {
            Long productId = Long.valueOf(productStr);
            try {
                // 获取商品扩展类
                ErpCollectProductExpand expand = erpCollectProductExpandMapper
                        .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                                .eq(ErpCollectProductExpand::getCollectProductId, productId));

                Integer isOptimize = expand.getIsOptimize();
//	            if (isOptimize.equals(0))
//	                return R.fail("商品未优化");
                if (expand.getIsUploadTest() != 2) {
                    errorList.add(productId);
                    continue;
                }
                ErpProductUnifiedTakedown erpProductUnifiedTakedown = erpProductUnifiedTakedownMapper
                        .selectOne(new LambdaQueryWrapper<ErpProductUnifiedTakedown>()
                                .eq(ErpProductUnifiedTakedown::getCollectProductId, productId)
                                .eq(ErpProductUnifiedTakedown::getIsEffective, 1).last("limit 1"));
                if (erpProductUnifiedTakedown != null) {
                    errorList.add(productId);
                    continue;
                }
                // 修改商品的sku和区域定价
                updateSkuProperty(productId);
                // 修改
                LambdaUpdateWrapper<ErpCollectProductExpand> luw = new LambdaUpdateWrapper<ErpCollectProductExpand>();
                luw.eq(ErpCollectProductExpand::getCollectProductId, productId);
                luw.set(ErpCollectProductExpand::getProductStatus, 1);
                erpCollectProductExpandMapper.update(null, luw);

                // 分割字符串,查看选择
                List<String> typeList = ListUtil.toList(type.split(","));
                if (typeList.size() > 0) {

                    Boolean typeFlag = typeList.stream().allMatch((typeStr) -> typeStr.equals("1"));
                    // 选择了1
                    if (typeFlag) {
                        // 调用接口，加入调价队列
                        //TODO Ae相关 改造为内部Api调用 暂不迁移
//                        addTaskForBatchGrounding(productId);
                    }

                    Boolean synchronizationFlag = typeList.stream().allMatch((typeStr) -> typeStr.equals("2"));
                    // 选择了2
                    if (synchronizationFlag) {
                        //TODO Ae相关 改造为内部Api调用
//                        aeProductEditService.synchronizationProductEdit(productId);
                    }
                }
            } catch (Exception e) {
                if (productIdList.size() == 1) {
                    return R.fail(e.getMessage());
                } else {
                    errorList.add(productId);
                }
            }
        }
        if (errorList.size() > 0) {
            String res = "上架成功个数：" + (productIdList.size() - errorList.size()) + ", 失败个数：" + errorList.size()
                    + " ,失败后请单个点击发布查看详细原因,失败id为：" + errorList.toString();
            return R.fail(res);
        } else {
            return R.ok("上架成功个数：" + productIdList.size());
        }
    }


    /**
     * 单个上架
     *
     * @param productIds
     * @param type
     * @return
     */
    public R<Object> oneGrounding(String productIds, String type) {
        Long productId = Long.valueOf(productIds);
        try {
            // 获取商品扩展类
            ErpCollectProductExpand expand = erpCollectProductExpandMapper
                    .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                            .eq(ErpCollectProductExpand::getCollectProductId, productId));

            Integer isOptimize = expand.getIsOptimize();
//	            if (isOptimize.equals(0))
//	                return R.fail("商品未优化");

            //获取商品的标签
            String classifyLabel = expand.getClassifyLabel();
            if (ObjectUtils.isNotNull(classifyLabel)) {
                //若不为空，则判断是否是2.0标签
                if (!classifyLabel.contains("1719179918137212929")) {
                    if (expand.getIsUploadTest() != 2) {
                        return R.fail("商品未测试发布");
                    }
                }
            }

            ErpProductUnifiedTakedown erpProductUnifiedTakedown = erpProductUnifiedTakedownMapper
                    .selectOne(new LambdaQueryWrapper<ErpProductUnifiedTakedown>()
                            .eq(ErpProductUnifiedTakedown::getCollectProductId, productId)
                            .eq(ErpProductUnifiedTakedown::getIsEffective, 1).last("limit 1"));
            if (erpProductUnifiedTakedown != null) {
                return R.ok(501, "处于系统统一下架状态，清先修复下架再进行上架");
            }
            // 修改商品的sku和区域定价
            updateSkuProperty(productId);
            // 修改
            LambdaUpdateWrapper<ErpCollectProductExpand> luw = new LambdaUpdateWrapper<ErpCollectProductExpand>();
            luw.eq(ErpCollectProductExpand::getCollectProductId, productId);
            luw.set(ErpCollectProductExpand::getProductStatus, 1);
            erpCollectProductExpandMapper.update(null, luw);

            // 分割字符串,查看选择
            List<String> typeList = ListUtil.toList(type.split(","));
            if (typeList.size() > 0) {

                Boolean typeFlag = typeList.stream().allMatch((typeStr) -> typeStr.equals("1"));
                // 选择了1
                if (typeFlag) {
                    // 调用接口，加入调价队列
                    //TODO Ae相关 改造为内部Api调用
//                    addTaskForBatchGrounding(productId);
                }

                Boolean synchronizationFlag = typeList.stream().allMatch((typeStr) -> typeStr.equals("2"));
                // 选择了2
                if (synchronizationFlag) {
                    //TODO Ae相关 改造为内部Api调用
//                    aeProductEditService.synchronizationProductEdit(productId);
                }

            }
        } catch (Exception e) {
            return R.fail("系统异常，请联系管理员");
        }
        return R.ok("上架成功");
    }

    @Async
    //采集库批量上传Oss图片
    public void updateProductUrl(Long collectProductId) {
        ErpCollectProduct collectProduct = baseMapper.selectById(collectProductId);
//        collectProduct.setMarketing(urlsToOssUrls(collectProduct.getMarketing()));
//        collectProduct.setImageURLs(urlsToOssUrls(collectProduct.getImageURLs()));
//        collectProduct.setWhite(urlsToOssUrls(collectProduct.getWhite()));
//        collectProduct.setDetailImg(urlsToOssUrls(collectProduct.getDetailImg()));
        LambdaUpdateWrapper<ErpCollectProduct> luw = Wrappers.lambdaUpdate();
        luw.set(ErpCollectProduct::getMarketing, urlsToOssUrls(collectProduct.getMarketing()));
        luw.set(ErpCollectProduct::getImageURLs, urlsToOssUrls(collectProduct.getImageURLs()));
        luw.set(ErpCollectProduct::getWhite, urlsToOssUrls(collectProduct.getWhite()));
//        if (!collectProduct.getDetailImg().contains("ae01")  &&  !collectProduct.getDetailImg().contains("common-product") ){
//            if (ObjectUtils.isNull(collectProduct.getOldDetailImg())){
//                luw.set(ErpCollectProduct::getOldDetailImg, collectProduct.getDetailImg());
//            }
//        }
        luw.set(ErpCollectProduct::getDetailImg, urlsToOssUrls(collectProduct.getDetailImg()));
        luw.eq(ErpCollectProduct::getId, collectProductId);
        baseMapper.update(null, luw);

        List<ErpCollectProductSku> erpCollectProductSkus = erpCollectProductSkuMapper
                .selectList(Wrappers.lambdaQuery(new ErpCollectProductSku())
                        .eq(ErpCollectProductSku::getCollectProductId, collectProduct.getId()));
        erpCollectProductSkus.forEach(erpCollectProductSku -> {
            erpCollectProductSku.setSkuImage(urlsToOssUrls(erpCollectProductSku.getSkuImage()));
            erpCollectProductSkuMapper.updateById(erpCollectProductSku);
        });
    }

    private String urlsToOssUrls(String urls) {
        if (Strings.isBlank(urls)) {
            return urls;
        }
        String[] urlArr = urls.split(";");
        List<String> urlList = new ArrayList<>();
        for (String url : urlArr) {
            if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("temp-product")) {
                if (url.contains("?")) {
                    url = url.substring(0, url.lastIndexOf("?"));
                }
                if (url.startsWith("temp-product")) {
                    url = "https:/file.pbb2c.com/" + url;
                }
                OssUrlDto dto = new OssUrlDto();
                dto.setOldUrl(url);
                R<Object> returnObj = remoteFileService.uploadUrl(dto);
                if (returnObj.getCode() != 200) {
                    return returnObj.getMsg();
                }
                String toJSONString = JSONObject.toJSONString(returnObj.getData());
                SysOss oss = JSONObject.parseObject(toJSONString, SysOss.class);
                urlList.add(oss == null ? url : oss.getUrl());
            } else {
                urlList.add(url);
            }
        }
        return String.join(";", urlList);
    }

    private LambdaQueryWrapper<ErpCollectProduct> buildQueryWrapper(ErpCollectProductBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpCollectProduct> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getId() != null, ErpCollectProduct::getId, bo.getId());
        lqw.eq(StringUtils.isNotBlank(bo.getImageURLs()), ErpCollectProduct::getImageURLs, bo.getImageURLs());
        lqw.like(StringUtils.isNotBlank(bo.getSubject()), ErpCollectProduct::getSubject, "%" + bo.getSubject() + "%");
        lqw.eq(StringUtils.isNotBlank(bo.getWhite()), ErpCollectProduct::getWhite, bo.getWhite());
        lqw.eq(StringUtils.isNotBlank(bo.getMarketing()), ErpCollectProduct::getMarketing, bo.getMarketing());
        lqw.eq(StringUtils.isNotBlank(bo.getMedia()), ErpCollectProduct::getMedia, bo.getMedia());
        lqw.eq(StringUtils.isNotBlank(bo.getCollectProductPrice()), ErpCollectProduct::getCollectProductPrice,
                bo.getCollectProductPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getMobileDetail()), ErpCollectProduct::getMobileDetail, bo.getMobileDetail());
        lqw.eq(bo.getPackageLength() != null, ErpCollectProduct::getPackageLength, bo.getPackageLength());
        lqw.eq(StringUtils.isNotBlank(bo.getPackageWidth()), ErpCollectProduct::getPackageWidth, bo.getPackageWidth());
        lqw.eq(bo.getPackageHeight() != null, ErpCollectProduct::getPackageHeight, bo.getPackageHeight());
        lqw.eq(StringUtils.isNotBlank(bo.getGrossWeight()), ErpCollectProduct::getGrossWeight, bo.getGrossWeight());
        lqw.eq(bo.getProductUnit() != null, ErpCollectProduct::getProductUnit, bo.getProductUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getCustomAttributes()), ErpCollectProduct::getCustomAttributes,
                bo.getCustomAttributes());
        lqw.eq(StringUtils.isNotBlank(bo.getDetail()), ErpCollectProduct::getDetail, bo.getDetail());
        lqw.eq(bo.getSizechartId() != null, ErpCollectProduct::getSizechartId, bo.getSizechartId());
        lqw.eq(StringUtils.isNotBlank(bo.getModeSizeChartList()), ErpCollectProduct::getModeSizeChartList,
                bo.getModeSizeChartList());
        lqw.eq(StringUtils.isNotBlank(bo.getCollectUrl()), ErpCollectProduct::getCollectUrl, bo.getCollectUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpCollectProduct::getRevision, bo.getRevision());

        lqw.eq(bo.getCollectUserId() != null, ErpCollectProduct::getCollectUserId, bo.getCollectUserId());

        // 价格区间查询
        if (StringUtils.isNotEmpty(bo.getProductPriceMin()))
            lqw.ge(ErpCollectProduct::getProductPrice, bo.getProductPriceMin());
        if (StringUtils.isNotEmpty(bo.getProductPriceMax()))
            lqw.le(ErpCollectProduct::getProductPrice, bo.getProductPriceMax());

        // 商品类目
        lqw.apply(bo.getCategoryId() != null,
                " category_id in (SELECT id FROM `erp_collect_product_category` WHERE id = " + bo.getCategoryId()
                        + " OR FIND_IN_SET( " + bo.getCategoryId() + " , ancestors ))");

        String expandSql = "";
        // 关键词
        String keyword = bo.getKeyword();
        if (StringUtils.isNotEmpty(keyword)) {
//			lqw.apply(" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE keyword like '%"
//					+ keyword + "%')");
            expandSql += " and keyword like '%" + keyword + "%' ";
        }

        // 是否为品牌（0是 1否）
        Integer isBrand = bo.getIsBrand();
        if (isBrand != null) {
            if (isBrand.equals(0)) {
//				lqw.apply(
//						" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE brand_id IS NOT NULL)");
                expandSql += " and brand_id IS NOT NULL ";
            } else {
//				lqw.apply(" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE brand_id IS NULL)");
                expandSql += " and brand_id IS NULL ";
            }
        }

        // 品牌id
        String brandId = bo.getBrandId();
        if (brandId != null) {
//			lqw.apply(" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE brand_id in( " + brandId
//					+ "))");
            expandSql += " and brand_id in( " + brandId + ") ";
        } else {
            // 品牌产品列表---品牌条件是否为空都作为条件查询
            if (bo.getModuleType() == 1) {
                lqw.apply(" id = null");
            }
        }
        // 是否已优化
        Integer isOptimize = bo.getIsOptimize();
        if (isOptimize != null) {
//			lqw.apply(" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE is_optimize = "
//					+ isOptimize + ")");
            expandSql += " and is_optimize = " + isOptimize + " ";
        }
        Integer isUploadTest = bo.getIsUploadTest();
        // 是否已发布测试
        if (isUploadTest != null) {
//			lqw.apply(" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE is_upload_test = "
//					+ isUploadTest + ")");
            expandSql += " and is_upload_test = " + isUploadTest + " ";
        }

        // 是否为发布产品
        Integer isGrounding = bo.getIsGrounding();
        if (isGrounding != null) {
//			lqw.apply(" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE product_status = "
//					+ isGrounding + ")");
            expandSql += " and product_status = " + isGrounding + " ";
        }

        // 是否为已编辑
        Integer isEdit = bo.getIsEdit();
        if (isEdit != null) {
//			if (isEdit.equals(0)) {
//				lqw.apply(" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE edit_status = "
//						+ isEdit + ")");
//			}else if (isEdit.equals(1)) {
//				lqw.apply(" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE edit_status = "
//						+ isEdit + ")");
//			}
            expandSql += " and edit_status = " + isEdit + " ";
        }

        // 是否自动优化
        Integer isAutoOptimize = bo.getIsAutoOptimize();
        if (isAutoOptimize != null) {
            expandSql += " and is_auto_optimize =" + isAutoOptimize + "";
        }

        // 查询类型
        Integer type = bo.getType();
        if (type != null) {
            if (type.equals(0)) {

            } else if (type.equals(1)) {
                lqw.eq(ErpCollectProduct::getDelFlag, 0); // 未删除的
            } else if (type.equals(2)) { // 已经编辑并且忽略优化的
                lqw.eq(ErpCollectProduct::getDelFlag, 0); // 未删除的
//				lqw.apply(
//						" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE edit_status = 1 and is_optimize != 2)");
                expandSql += " and edit_status = 1 and is_optimize != 2 ";
            } else if (type.equals(3)) {
                lqw.eq(ErpCollectProduct::getDelFlag, 0); // 未删除的
                expandSql += " and edit_status = 2 ";
            }
        }

        // 是否为已运费试算
        Integer isFreight = bo.getIsFreight();
        if (isFreight != null) {
//			lqw.apply(" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE is_freight = "
//					+ isFreight + ")");
            expandSql += " and is_freight = " + isFreight + " ";
        }

        // 是否为已翻译
        Integer isTranslate = bo.getIsTranslate();
        if (isTranslate != null) {
//			lqw.apply(" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE is_translate = "
//					+ isTranslate + ")");
            expandSql += " and is_translate = " + isTranslate + " ";
        }

        Integer templateType = bo.getTemplateType();
        if (templateType != null) {
            if (templateType.equals(1)) // 标准
//				lqw.apply(
//						" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE template_id in (0,1,2))");
                expandSql += " and template_id in (0,1,2) ";
            else if (templateType.equals(2)) // 大包
//				lqw.apply(
//						" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE template_id in (3))");
                expandSql += " and template_id = 3 ";
            else if (templateType.equals(3)) // 经济
//				lqw.apply(
//						" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE template_id in (4,5))");
                expandSql += " and template_id in (4,5) ";
        }

        // 添加expandSql
        if (StringUtils.isNotEmpty(expandSql)) {
            expandSql = expandSql.substring(4);
            lqw.apply(" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE " + expandSql + ")");
        }

        //标签
        String classifyLabel = bo.getClassifyLabel();
        if (StringUtils.isNotEmpty(classifyLabel)) {
            lqw.apply(" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE classify_label  like '%" + classifyLabel + "%')");
        }

        // 是否上架
        String onShelf = bo.getOnShelf();
        if (StringUtils.isNotEmpty(onShelf)) {
            if ("0".equals(onShelf)) {
                lqw.apply("id in (select collect_product_id from erp_seller_product sp where sp.seller_id = "
                        + SecurityUtils.getUserId() + " )");
            } else {
                lqw.apply("id not in (select collect_product_id from erp_seller_product sp where sp.seller_id = "
                        + SecurityUtils.getUserId() + " )");
            }
        }

        // 是否为采集商品（0是 1否）
        Integer isCollect = bo.getIsCollect();
        if (isCollect != null) {
            if (isCollect.equals(0))
                lqw.isNotNull(ErpCollectProduct::getCollectUrl);
            else
                lqw.isNull(ErpCollectProduct::getCollectUrl);
        }

        // 自动抠图
        Integer isMatting = bo.getIsMatting();
        if (isMatting != null) {
            if (isMatting == 0 || isMatting == 1) { // 加入抠图/ 抠图完成
                lqw.apply("id in (SELECT collect_product_id FROM erp_collect_product_optimize_task WHERE `status` = "
                        + isMatting + ")");
            } else { // 未加入抠图
                lqw.apply("id not in (SELECT collect_product_id FROM erp_collect_product_optimize_task)"); // 未加入抠图
            }
        }

        // 指派任务是否完成
        Integer isCompleteTask = bo.getIsCompleteTask();
        if (isCompleteTask != null) {
            if (isCompleteTask.intValue() == 1) {
                // 已完成 1
                lqw.apply("id in (SELECT aaa.collect_product_id FROM ("
                        + "SELECT collect_product_id, count(`status`) c, SUM(`status`) s FROM erp_collect_product_optimize_plan "
                        + "GROUP BY collect_product_id HAVING c*3 = s) aaa)");
            } else if (isCompleteTask.intValue() == 0) {
                // 未完成 0
                lqw.apply("id in (SELECT aaa.collect_product_id FROM ("
                        + "SELECT collect_product_id, count(`status`) c, SUM(`status`) s FROM erp_collect_product_optimize_plan "
                        + "GROUP BY collect_product_id HAVING c*3 <> s) aaa)");
            } else {
                // 未指派 2
                lqw.apply("id NOT IN (SELECT DISTINCT collect_product_id FROM erp_collect_product_optimize_plan)");
            }
        }

        // skuCode
        String skuCode = bo.getSkuCode();
        if (StringUtils.isNotEmpty(skuCode)) {
            lqw.apply(" id in (SELECT collect_product_id FROM erp_collect_product_sku WHERE sku_code = '" + skuCode
                    + "')");
        }

//        String roles = LoginHelper.getRoles();
//        // 如果是采集主管，不能看商家采集的未出单的，也就是operate_type=1的
//        if (roles.contains("gather-responsible")) {
//            lqw.ne(ErpCollectProduct::getOperateType, 1);
//        }

        // 排序：1价格排序正序 2价格排序倒序 3时间排序正序 3时间排序倒序
        Integer orderBy = bo.getOrderBy();
        if (orderBy != null) {
            if (orderBy.equals(1)) // 价格排序正序
                lqw.last(" ORDER BY CONVERT(SUBSTRING_INDEX(product_price,'-',1), DECIMAL(10,2)) ASC ");
            else if (orderBy.equals(2)) // 价格排序倒序
                lqw.last(" ORDER BY CONVERT(SUBSTRING_INDEX(product_price,'-',1), DECIMAL(10,2)) DESC ");
            else if (orderBy.equals(3)) // 时间排序正序
                lqw.orderByAsc(ErpCollectProduct::getCreateTime);
            else if (orderBy.equals(4)) // 时间排序倒序
                lqw.orderByDesc(ErpCollectProduct::getCreateTime);
        } else {
            // 删除的排在后面
            lqw.orderByAsc(ErpCollectProduct::getDelFlag);

            lqw.orderByDesc(ErpCollectProduct::getUpdateTime);
        }

        return lqw;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpCollectProduct entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    @Override
    public void publish(String productIds, Long sellerId, Integer isAI, String roles) {
        List<String> asList = Arrays.asList(productIds.split(","));
        for (String string : asList) {
            publish(Long.valueOf(string), sellerId, isAI, 1, roles, null);
        }
    }

    @Override
    @Transactional
    public void publish(Long productId, Long sellerId, Integer isAI, Integer isGenerate, String roles, String taskId) {
        try {

            ErpCollectProductPublishTask publishTask = null;

            // 判断是否刊登过
            ErpSellerProduct sellerProduct = erpSellerProductMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerProduct>().eq(ErpSellerProduct::getCollectProductId, productId)
                            .eq(ErpSellerProduct::getSellerId, sellerId).last("limit 1"));
            if (sellerProduct != null) {
                // 产品发布个人产品记录日志数据为发布失败
                iErpCollectProductPublishTaskService.insertData(productId,
                        sellerId, PublishType.FAIL.getCode(), new Date(), "该产品您已刊登，不能重复刊登！");
                return;
            }
            // 产品发布个人产品记录日志数据为发布中
            publishTask = iErpCollectProductPublishTaskService.insertData(productId,
                    sellerId, PublishType.ONGOING.getCode(), new Date(), null);

//            // 创建产品发布个人产品记录日志数据
//            ErpCollectProductPublishTask publishTask = iErpCollectProductPublishTaskService.insertData(productId,
//                    sellerId, PublishType.ONGOING.getCode(), new Date());
//
//                // 产品发布个人产品记录日志数据更新为发布失败
//                collectProductPublishTaskMapper.update(publishTask,
//                        new LambdaUpdateWrapper<ErpCollectProductPublishTask>()
//                                .set(ErpCollectProductPublishTask::getStatus, PublishType.FAIL.getCode())
//                                .set(ErpCollectProductPublishTask::getRemark, "该产品您已刊登，不能重复刊登！")
//                                .eq(ErpCollectProductPublishTask::getId, publishTask.getId()));
//                return;
//            }

            // 刊登以前再次上传图片
            updateProductUrl(productId);


            // 获取商品
            ErpCollectProduct product = baseMapper.selectById(productId);
            // 获取sku列表
            List<ErpCollectProductSkuVo> productVoSkus = erpCollectProductSkuMapper
                    .selectVoList(new LambdaQueryWrapper<ErpCollectProductSku>()
                            .eq(ErpCollectProductSku::getCollectProductId, productId));
            // 获取产品扩展表
            ErpCollectProductExpandVo collectProductExpandVo = erpCollectProductExpandMapper
                    .selectVoOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                            .eq(ErpCollectProductExpand::getCollectProductId, productId));

            // 保存卖家商品库中
            ErpSellerProduct erpSellerProduct = new ErpSellerProduct();
            BeanUtils.copyProperties(product, erpSellerProduct);
            erpSellerProduct.setSellerId(sellerId);
            erpSellerProduct.setCollectProductId(productId);
            erpSellerProduct.setId(null);
//		erpSellerProduct.setCreateTime(null);
            erpSellerProduct.setUpdateTime(new Date());
            erpSellerProduct.setCreateBy(sellerId + "");
            erpSellerProduct.setUpdateBy(sellerId + "");

            // 获取当前登陆的用户的角色
            if (roles.contains("erp-user")) { // erp用户才调换位置
                String urls = erpSellerProduct.getImageURLs();
                List<String> asList = Arrays.asList(urls.split(";"));
                Collections.shuffle(asList);
                String collect = asList.stream().collect(Collectors.joining(";"));
                erpSellerProduct.setImageURLs(collect);
            }

            Integer isOptimize = collectProductExpandVo.getIsOptimize();
            if (isAI.equals(1)) {
                /** 合并创建新图片 start **/
                String tempWhite = null;
                String tempMarketing = null;
                if (isOptimize == 2 || isOptimize == 0) {
                    tempMarketing = erpSellerProduct.getMarketing();
                    tempWhite = erpSellerProduct.getWhite();
                } else {
                    tempWhite = ImageMerge(erpSellerProduct.getMarketing(), erpSellerProduct.getSellerId(),
                            erpSellerProduct.getCollectProductId());
                    tempMarketing = ImageMerge(erpSellerProduct.getWhite(), erpSellerProduct.getSellerId(),
                            erpSellerProduct.getCollectProductId());
                }
                erpSellerProduct.setImageURLs(ImageMerge(erpSellerProduct.getImageURLs(),
                        erpSellerProduct.getSellerId(), erpSellerProduct.getCollectProductId()));
                erpSellerProduct.setWhite(tempWhite);
                erpSellerProduct.setMarketing(tempMarketing);
                erpSellerProduct.setDetailImg(ImageMerge(erpSellerProduct.getDetailImg(),
                        erpSellerProduct.getSellerId(), erpSellerProduct.getCollectProductId()));
                /** 合并创建新图片 end **/
            }

            if (isGenerate.equals(1)) {
                /** AI生成新标题和详情 start */
                String keyword = collectProductExpandVo.getKeyword();
                String detailKeyword = collectProductExpandVo.getDetailKeyword();

                // 判断关键词个数，关键词太多也不行
                try {
//                    if (StringUtils.isNotEmpty(keyword)) {
//                        if (keyword.length() > 60) // 超过60，截取
//                            while (keyword.lastIndexOf(",") > 65 || keyword.length() > 60) {
//                                if (keyword.lastIndexOf(",") < 50)
//                                    keyword = keyword.substring(0, 60);
//                                else
//                                    keyword = keyword.substring(0, keyword.lastIndexOf(","));
//                                if (keyword.length() < 70)
//                                    break;
//                            }
//                         根据关键词生成新的128个字符的新标题
//                        String subject = ChatGptUtils.createTitle(keyword);
//                         根据旧标题，生成新标题 TODO 取消，暂未换位置
                    String subject = ChatGptUtils.createTitle(product.getSubject());
                    if (subject.length() > 128) {
                        subject = subject.substring(0, 120);
                    }
//                    }

                    if (StringUtils.isNotEmpty(subject)) {
                        //调用孙哥接口判断
                        R<Object> objectR = iErpPythonMethodCallService.checkViolationWords(subject);
                        if (objectR.getCode() == 200) {
                            //没有侵权词
                            erpSellerProduct.setSubject(subject);
                        } else {
                            //有侵权词
                            iErpCollectProductPublishTaskService.insertData(productId,
                                    sellerId, PublishType.FAIL.getCode(), new Date(), "公共库产品有侵权词，请确认");
                            return;
                        }
                    } else {
                        erpSellerProduct.setSubject(product.getSubject());
                    }
                } catch (Exception e) {

                }
                try {
                    if (StringUtils.isNotEmpty(detailKeyword)) {
                        String detail = ChatGptUtils.createProductDescription(detailKeyword);
                        if (StringUtils.isNotEmpty(detail))
                            erpSellerProduct.setDetail(detail);
                    }
                } catch (Exception e) {

                }
                /** AI生成新标题和详情 end */
            }

            erpSellerProductMapper.insert(erpSellerProduct);

            Map<String, BigDecimal> skuPriceMap = new HashedMap<>();
            String freightMap = collectProductExpandVo.getFreightMap();
            List<Dict> freightMapList = JsonUtils.parseArrayMap(freightMap);

            // 获取运费，修改金额
            for (Dict dict : freightMapList) {
                Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                for (String key : absoluteQuoteMap.keySet()) {
                    BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());

                    // 添加sku价格
                    if (skuPriceMap.containsKey(key)) {
                        BigDecimal price = skuPriceMap.get(key);
                        if (price.compareTo(amount) == 1)
                            skuPriceMap.put(key, amount);
                    } else {
                        skuPriceMap.put(key, amount);
                    }
                }
            }

            // 保存sku
            for (ErpCollectProductSkuVo erpCollectProductSkuVo : productVoSkus) {
                ErpSellerProductSku erpSellerProductSku = new ErpSellerProductSku();
                BeanUtils.copyProperties(erpCollectProductSkuVo, erpSellerProductSku);
                erpSellerProductSku.setId(null);
                erpSellerProductSku.setSellerProductId(erpSellerProduct.getId());
                erpSellerProductSku.setCreateTime(null);
                erpSellerProductSku.setUpdateTime(null);
                erpSellerProductSku.setCreateBy(sellerId + "");
                erpSellerProductSku.setUpdateBy(sellerId + "");

                String skuPropertyIds = erpSellerProductSku.getSkuPropertyIds();
                if (skuPriceMap.containsKey(skuPropertyIds)) {
                    BigDecimal minPrice = skuPriceMap.get(skuPropertyIds);

                    // 获取sku
                    BigDecimal skuPrice = new BigDecimal(erpSellerProductSku.getSkuPrice());
                    skuPrice = skuPrice.multiply(new BigDecimal(1.1));

                    // 计算最终价格
                    BigDecimal amount = skuPrice.add(minPrice.multiply(new BigDecimal(1.5))).setScale(2,
                            BigDecimal.ROUND_HALF_UP);
                    erpSellerProductSku.setSkuPrice(amount.toString());
                }

                erpSellerProductSkuMapper.insert(erpSellerProductSku);
            }

            // 保存商品扩展类
            ErpSellerProductExpand erpSellerProductExpand = new ErpSellerProductExpand();
            BeanUtils.copyProperties(collectProductExpandVo, erpSellerProductExpand);
            erpSellerProductExpand.setId(null);
            erpSellerProductExpand.setSellerProductId(erpSellerProduct.getId());
            erpSellerProductExpand.setAutoTaskId(taskId);
            erpSellerProductExpand.setCreateTime(null);
            erpSellerProductExpand.setUpdateTime(null);
            erpSellerProductExpand.setCreateBy(sellerId + "");
            erpSellerProductExpand.setUpdateBy(sellerId + "");
            erpSellerProductExpandMapper.insert(erpSellerProductExpand);

            // TODO 产品发布个人产品记录日志数据更新为发布成功
            // 产品发布个人产品记录日志数据更新为发布失败
            collectProductPublishTaskMapper.update(publishTask,
                    new LambdaUpdateWrapper<ErpCollectProductPublishTask>()
                            .set(ErpCollectProductPublishTask::getStatus, PublishType.SUCCESS.getCode())
                            .eq(ErpCollectProductPublishTask::getId, publishTask.getId()));
            // 将视频上传至媒体中心
//			try {
//				iAeMediacenterService.videoUploadByUR(erpSellerProduct.getId());
//			} catch (Exception e) {
//				System.out.println(erpSellerProduct.getId() + "视频上传异常");
//			}

        } catch (
                Exception e) {

        }

    }

    @Override
    public void publishAuto(
            String productIds, String userId, String taskId
    ) {

        List<String> asList = Arrays.asList(productIds.split(","));
        for (String string : asList) {

            publish(Long.valueOf(string), Long.valueOf(userId), 1, 1, "erp-user", taskId.toString());

        }
    }

    @Override
    public String ImageMerge(String oldPicUrls, Long sellerId, Long collectProductId) {
        List<ErpSellerReplaceImageRecord> replaceList = new ArrayList<>();
        ErpSellerReplaceImageRecord sellerReplaceImageRecord = null;
        /**
         * 合成图片处理流程 1、根据传入的原始图片，进行图片分割 2、根据单一图片，获取对应的多张元素图片和对应的背景图标签
         * 3、分割元素图，并随机一张图片（当前默认选择第一张，后期再修改） 4、根据对应的背景图标签，获取该标签下的所有图片地址
         * 5、随机挑选一张背景图，并进行合并处理 6、将临时图片上传至oss并覆盖原图片 7、删除临时图片
         */
        // 元素图
        String elementPic = "";
        // 背景图
        String backgroundPic = "";
        // 新图地址集合
        String newPicUrls = "";
        ErpCollectProductOptimize collectProductOptimize = null;
        // 1、轮播图
        if (oldPicUrls != null && !oldPicUrls.trim().equals("")) {
            // 1、将传入图片进行分割
            String picUrl[] = oldPicUrls.split(";");

//			ExecutorService executorService = Executors.newFixedThreadPool(10);
//			ArrayList<Future<List<String>>> list = new ArrayList<>();
            try {
                for (String url : picUrl) {
                    sellerReplaceImageRecord = new ErpSellerReplaceImageRecord();
                    // 2、获取该图片对应的元素图和背景图标签集合
                    try {
                        collectProductOptimize = collectProductOptimizeMapper.queryByOptimizePic(url, collectProductId);
                        if (collectProductOptimize == null || collectProductOptimize.getPics() == null
                                || collectProductOptimize.getPics().equals("")
                                || collectProductOptimize.getTagIds() == null
                                || collectProductOptimize.getTagIds().equals("")) {
                            // 如果没有适合合并的图片，需要把原来的图片继续存到集合里
                            newPicUrls = newPicUrls + ";" + url;
                            continue;
                        } else {
                            // 3、暂时获取第一张元素图
                            elementPic = getOssUrlHeader() + "/" + collectProductOptimize.getPics().split(";")[0];
                            // 4、根据标签随机获取一张背景图
                            backgroundPic = getOssUrlHeader() + "/"
                                    + getBackgroundPic(collectProductOptimize.getTagIds(),
                                    collectProductOptimize.getType().intValue() == 2 ? 1
                                            : collectProductOptimize.getType().intValue());
                        }
                        // 根据元素图和背景图，合并图片 url.substring(url.lastIndexOf("/")+1
//					String newPicUrl = tempPicPath + "" + url.replaceAll("/", "_");
                        String newPicUrl = urlConfig.getTempPicPath() + "" + IdUtil.fastSimpleUUID() + ".jpg";
                        try {
                            ImageMergeUtils.overlyingImageTest(backgroundPic, elementPic, newPicUrl);
                            // 6、将临时图片上传OSS并获取到最新路径并删除临时图片
                            String mergeUrl = uploadNewPicToOss(newPicUrl);
                            newPicUrls = newPicUrls + ";" + mergeUrl;

                            // 7、插入记录
                            sellerReplaceImageRecord.setCollectProductId(collectProductId);
                            sellerReplaceImageRecord.setSellerId(sellerId);
                            sellerReplaceImageRecord.setOldUrl(url);
                            sellerReplaceImageRecord.setNewUrl(mergeUrl);
                            sellerReplaceImageRecord.setTransparentUrl(collectProductOptimize.getPics().split(";")[0]);
                            replaceList.add(sellerReplaceImageRecord);
                        } catch (Exception e) {
                            System.out.println("*****************backgroundPic=" + backgroundPic);
                            System.out.println("*****************elementPic=" + elementPic);
                            // 合并失败后，保留原图链接
                            newPicUrls = newPicUrls + ";" + url;
                        }
                    } catch (Exception e) {
                        System.out.println("*****************backgroundPic=" + backgroundPic);
                        System.out.println("*****************elementPic=" + elementPic);
                        // 合并失败后，保留原图链接
                        newPicUrls = newPicUrls + ";" + url;
                    }

//					Callable<List<String>> callable1 = () -> overlyingImage(url, sellerId, collectProductId,
//							replaceList);
////					FutureTask<String> task1 = new FutureTask<>(callable1);
//					Future<List<String>> submit = executorService.submit(callable1);
//					list.add(submit);
                }
//				for (Future<List<String>> future : list) {
//					List<String> resList = future.get();
//					if (resList.size() > 1) {
//						oldPicUrls = oldPicUrls.replace(resList.get(0), resList.get(1));
//					}
//				}
            } catch (Exception e) {
            }
            sellerReplaceImageRecordMapper.insertBatch(replaceList);
            return newPicUrls.substring(1);
        }
        return oldPicUrls;
    }

    @Override
    public R<Object> getCollectProductInfoById(Long id) {
        ErpCollectProduct erpCollectProduct = baseMapper.selectById(id);
        if (Objects.isNull(erpCollectProduct)) {
            return R.fail("获取信息失败");
        } else {
            return R.ok(erpCollectProduct);
        }
    }

    @Override
    public void setProToOrder(String skuCode) {

        // 根据skucode获取商品id
        ErpCollectProductSku collectProductSku = erpCollectProductSkuMapper
                .selectOne(new LambdaQueryWrapper<ErpCollectProductSku>()
                        .eq(ErpCollectProductSku::getSkuCode, skuCode)
                        .eq(ErpCollectProductSku::getDelFlag, "0")
                        .last("limit 1"));
        if (collectProductSku == null)
            return;

        // 获取商品的信息
        ErpCollectProduct product = baseMapper.selectById(collectProductSku.getCollectProductId());
        Integer operateType = product.getOperateType();

        if (operateType.equals(1)) {
            operateType = 2;
            product.setOperateType(operateType);
            baseMapper.updateById(product);
        }
    }

    @Override
    public String getCategoryEn(Long collectProductId) {

        return baseMapper.getCategoryEn(collectProductId);
    }

    @Override
    public String getCategoryCN(Long collectProductId) {
        return baseMapper.getCategoryCN(collectProductId);
    }

    /**
     * 根据标签获取背景图，路径必然为oss相对路径
     *
     * @param tagIds
     * @return
     */
    private String getBackgroundPic(String tagIds, Integer type) {
        if (type.intValue() == 3) {
            // 白底图
            return "common-product/2023/04/25/A3A9697071CE415794AD88EA8192C309.jpg";
        }
        List<Long> idList = Arrays.stream(tagIds.split(",")).map(s -> Long.parseLong(s.trim()))
                .collect(Collectors.toList());
        Long[] ids = idList.toArray(new Long[idList.size()]);
        List<ErpProductAtlas> productAtlasList = erpProductAtlasMapper.getBackgroundPicList(ids, type);
        int atlasCount = productAtlasList.size();
        if (atlasCount < 1) {
            return "";
        }
        Random rand = new Random();
        int bgNum = rand.nextInt(atlasCount - 1);
        return productAtlasList.get(bgNum).getPictureUrl();
    }

    private String getOssUrlHeader() {
//       TODO oss相关 内部服务调用 待测试
        R<Object> ossUrlHeader = remoteFileService.getOssUrlHeader();
        if (ossUrlHeader.getCode() != 200) {
            return "获取oss信息失败";
        }
        return ossUrlHeader.getData().toString();
    }


    @Override
    public void selectEditProductUrlToOss() {
        // 获取已经编辑的商品
        LambdaQueryWrapper<ErpCollectProduct> lqw = new LambdaQueryWrapper<ErpCollectProduct>();
        lqw.select(ErpCollectProduct::getId);
        lqw.like(ErpCollectProduct::getImageURLs, "http");
        lqw.apply("id in (SELECT collect_product_id FROM `erp_collect_product_expand` WHERE edit_status=1)");
        List<ErpCollectProduct> selectList = baseMapper.selectList(lqw);
        for (ErpCollectProduct erpCollectProduct : selectList) {
            Long collectProductId = erpCollectProduct.getId();
            ErpCollectProduct collectProduct = baseMapper.selectById(collectProductId);
            collectProduct.setMarketing(updateOptimizeUrl(collectProduct.getMarketing(), 3, collectProductId));
            collectProduct.setImageURLs(updateOptimizeUrl(collectProduct.getImageURLs(), 0, collectProductId));
            collectProduct.setWhite(updateOptimizeUrl(collectProduct.getWhite(), 2, collectProductId));
            collectProduct.setDetailImg(updateOptimizeUrl(collectProduct.getDetailImg(), 1, collectProductId));
            baseMapper.updateById(collectProduct);

            List<ErpCollectProductSku> erpCollectProductSkus = erpCollectProductSkuMapper
                    .selectList(Wrappers.lambdaQuery(new ErpCollectProductSku())
                            .eq(ErpCollectProductSku::getCollectProductId, collectProduct.getId()));
            erpCollectProductSkus.forEach(erpCollectProductSku -> {
                erpCollectProductSku.setSkuImage(urlsToOssUrls(erpCollectProductSku.getSkuImage()));
                erpCollectProductSkuMapper.updateById(erpCollectProductSku);
            });
        }
    }


    public String updateOptimizeUrl(String urls, Integer type, Long collectProductId) {
        if (Strings.isBlank(urls)) {
            return urls;
        }
        String[] urlArr = urls.split(";");
        List<String> urlList = new ArrayList<>();
        for (String url : urlArr) {
            if (url.startsWith("http://") || url.startsWith("https://")) {
                if (url.contains("?")) {
                    url = url.substring(0, url.lastIndexOf("?"));
                }
                OssUrlDto dto = new OssUrlDto();
                dto.setOldUrl(url);
                R<Object> returnObj = remoteFileService.uploadUrl(dto);
                if (returnObj.getCode() != 200) {
                    return returnObj.getMsg();
                }
                String toJSONString = JSONObject.toJSONString(returnObj.getData());
                SysOssVo sysOssVo = JSONObject.parseObject(toJSONString, SysOssVo.class);
                urlList.add(sysOssVo == null ? url : sysOssVo.getUrl());

                // 修改元素图对应
                LambdaQueryWrapper<ErpCollectProductOptimize> lwq = new LambdaQueryWrapper<ErpCollectProductOptimize>();
                lwq.eq(ErpCollectProductOptimize::getCollectProductId, collectProductId);
                lwq.eq(ErpCollectProductOptimize::getOptimizePic, url);
                lwq.eq(ErpCollectProductOptimize::getType, type);
                lwq.last("limit 1");
                ErpCollectProductOptimize optimize = collectProductOptimizeMapper.selectOne(lwq);
                if (optimize != null) {
                    optimize.setOptimizePic(sysOssVo == null ? url : sysOssVo.getUrl());
                    collectProductOptimizeMapper.updateById(optimize);
                }
            } else {
                urlList.add(url);
            }
        }
        return String.join(";", urlList);
    }

    @Override
    public void ignoreTranslation(Long productId) {
        LambdaUpdateWrapper<ErpCollectProductExpand> luw = new LambdaUpdateWrapper<ErpCollectProductExpand>();
        luw.set(ErpCollectProductExpand::getIsTranslate, 4);
        luw.eq(ErpCollectProductExpand::getCollectProductId, productId);
        erpCollectProductExpandMapper.update(null, luw);
    }

    @Override
    public Boolean checkProductUploadTest(Long collectProductId, Integer type) {
        if (type == 1) {
            ErpCollectProductExpand productExpand = erpCollectProductExpandMapper.selectOne(
                    new LambdaQueryWrapper<ErpCollectProductExpand>().eq(ErpCollectProductExpand::getCollectProductId, collectProductId));
            if (productExpand.getClassifyLabel().contains("1719179918137212929")) {
                return true;
            }
            //有2.0产品标签
            productExpand = erpCollectProductExpandMapper
                    .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                            .eq(ErpCollectProductExpand::getCollectProductId, collectProductId)
//							.in(ErpCollectProductExpand::getIsOptimize, 1, 2)
                            .eq(ErpCollectProductExpand::getIsFreight, 3)
                            .in(ErpCollectProductExpand::getIsTranslate, 3, 4)
                            .eq(ErpCollectProductExpand::getEditStatus, 1));
            if (productExpand != null) {
                return true;
            } else {
                return false;
            }
        } else {
            ErpSellerCollectProductExpand productExpand = erpSellerCollectProductExpandMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerCollectProductExpand>().eq(ErpSellerCollectProductExpand::getCollectProductId, collectProductId));
            if (productExpand.getClassifyLabel().contains("1719179918137212929")) {
                return true;
            }
            productExpand = erpSellerCollectProductExpandMapper
                    .selectOne(new LambdaQueryWrapper<ErpSellerCollectProductExpand>()
                            .eq(ErpSellerCollectProductExpand::getCollectProductId, collectProductId)
                            .eq(ErpSellerCollectProductExpand::getIsFreight, 3)
                            .in(ErpSellerCollectProductExpand::getIsTranslate, 3, 4)
                            .eq(ErpSellerCollectProductExpand::getEditStatus, 1));
            if (productExpand != null) {
                return true;
            } else {
                return false;
            }
        }
    }

    @Override
    public Integer updateUploadTestStatus(Long collectProductId) {
        ErpCollectProductExpand erpCollectProductExpand = erpCollectProductExpandMapper
                .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                        .eq(ErpCollectProductExpand::getCollectProductId, collectProductId));
        erpCollectProductExpand.setIsUploadTest(1);
        if (erpCollectProductExpandMapper.updateById(erpCollectProductExpand) == 1) {
            return 1;
        } else {
            return 0;
        }
    }


    @Override
    @Async
    public void pushSkuPrice() {
        // 获取所有上架的商品
        List<ErpCollectProductExpand> expandList = erpCollectProductExpandMapper.selectList(
                new LambdaQueryWrapper<ErpCollectProductExpand>().eq(ErpCollectProductExpand::getIsFreight, 3));
        for (ErpCollectProductExpand expand : expandList) {
            try {
                iErpCollectProductSkuPriceService.saveSkuPrice(expand.getCollectProductId());
            } catch (Exception e) {
                System.out.println("productId: " + expand.getCollectProductId());
                e.printStackTrace();
            }
        }
    }

    @Override
    public void updateCateGoryPro() {
        List<Long> cateGoryList = Arrays.asList(new Long[]{201222631l, 100004777l, 100005864l});
        LambdaQueryWrapper<ErpCollectProduct> lqw = Wrappers.lambdaQuery();
        lqw.in(ErpCollectProduct::getCategoryId, cateGoryList);
        List<ErpCollectProduct> proList = baseMapper.selectList(lqw);

        for (ErpCollectProduct erpCollectProduct : proList) {
            updateCateGoryProById(erpCollectProduct);
        }
    }

    @Override
    public void updateCateGoryProById(Long proId) {
        ErpCollectProduct collectProduct = baseMapper.selectById(proId);
        updateCateGoryProById(collectProduct);
    }

    public void updateCateGoryProById(ErpCollectProduct erpCollectProduct) {
        try {

            // 获取扩展类和sku列表
            Long proId = erpCollectProduct.getId();

            ErpCollectProductExpand expand = erpCollectProductExpandMapper
                    .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                            .eq(ErpCollectProductExpand::getCollectProductId, proId).last(" limit 1 "));

            List<ErpCollectProductSku> skuList = erpCollectProductSkuMapper
                    .selectList(new LambdaQueryWrapper<ErpCollectProductSku>()
                            .eq(ErpCollectProductSku::getCollectProductId, proId));

            // 判断是否是多规格，不是就跳过
            ErpCollectProductSku erpCollectProductSku = skuList.get(0);
            String skuPropertyIds = erpCollectProductSku.getSkuPropertyIds();
            if (!skuPropertyIds.contains(";"))
                return;

            // 多规格合并为单规格
            String skuProperty = expand.getSkuProperty();

            // 解析合并
            Map<String, Long> map = new HashMap<>();

            Long value = 30000l;

            List<Dict> propertyList = JsonUtils.parseArrayMap(skuProperty);
            Dict dict = propertyList.get(0);
            List<HashMap<String, Object>> oneValue = (List<HashMap<String, Object>>) dict.get("list");

            List<HashMap<String, Object>> res = new ArrayList<>();
            for (int i = 1; i < propertyList.size(); i++) {
                Dict dict1 = propertyList.get(i);
                List<HashMap<String, Object>> otherValue = (List<HashMap<String, Object>>) dict1.get("list");

                // 合并
                for (HashMap<String, Object> map1 : oneValue) {
                    String name = (String) map1.get("name");
                    Object value1 = map1.get("value");

                    for (HashMap<String, Object> map2 : otherValue) {

                        HashMap<String, Object> newHashMap = new HashMap<>();

                        String name2 = (String) map2.get("name");

                        String nameres = name + " " + name2;
                        newHashMap.put("name", nameres);
                        newHashMap.put("value", value);

                        Object value2 = map2.get("value");

                        String key = value1 + "-" + value2;
                        map.put(key, value);

                        value++;

                        res.add(newHashMap);
                    }
                }
            }

            dict.put("list", res);
            propertyList = new ArrayList<Dict>();
            propertyList.add(dict);
            expand.setSkuProperty(JsonUtils.toJsonString(propertyList));

            // 修改sku
            for (ErpCollectProductSku sku : skuList) {

                String nameId = "";
                String valueId = "";

                // 获取sku属性
                String skuPropertyIds2 = sku.getSkuPropertyIds();
                String[] split = skuPropertyIds2.split(";");
                for (int i = 0; i < split.length; i++) {
                    String[] split2 = split[i].split(":");
                    if (i == 0) {
                        nameId = split2[0];
                    }
                    valueId = valueId + split2[1] + "-";
                }

                valueId = valueId.substring(0, valueId.length() - 1);

                // 获取新的id
                Long long1 = map.get(valueId);

                String newSkuPropertyIds = nameId + ":" + long1;
                sku.setSkuPropertyIds(newSkuPropertyIds);

            }

            // 更新扩展表和sku表
            erpCollectProductExpandMapper.updateById(expand);
            erpCollectProductSkuMapper.updateBatchById(skuList);

            // 获取编辑状态
            Integer editStatus = expand.getEditStatus();
            if (editStatus.equals(1)) {
                // 重新运费试算
                //TODO 运费相关 内部接口调用
//                erpCollectProductFreightTaskService.refresh(proId, 1);
                // 重新翻译
                iErpCollectProductTranslateTaskService.refresh(proId, 1);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Override
    public void updateRepeatSkuCode() {
        // 获取重复的sku的集合
        LambdaQueryWrapper<ErpCollectProductSku> lqw = new LambdaQueryWrapper<ErpCollectProductSku>();
        lqw.apply(
                "sku_code in (SELECT a.`sku_code` FROM `erp_collect_product_sku` a  GROUP BY a.`sku_code` HAVING COUNT(1) > 1)");
        List<ErpCollectProductSku> list = erpCollectProductSkuMapper.selectList(lqw);

        Map<String, String> map = new HashMap<>();
        List<ErpCollectProductSku> resList = new ArrayList<>();
        list.forEach(sku -> {
            String skuCode = sku.getSkuCode();
            // 判断是不是第一个
            if (map.containsKey(skuCode)) { // 包含，说明不是第一个，重新设置code
                sku.setSkuCode(CommonUtils.getSkuCode());
                resList.add(sku);
            } else { // 不包含，说明第一个，跳过
                map.put(skuCode, skuCode);
            }
        });
        erpCollectProductSkuMapper.updateBatchById(resList);
    }

    @Override
    public void addToSellerPro(String prods) {
        List<String> prodList = Arrays.asList(prods.split(","));
//		List<Long> remList = new ArrayList<Long>();

        for (String proId : prodList) {
            ErpCollectProduct collectProduct = baseMapper.selectById(proId);

            collectProduct.setCollectUserId(SecurityUtils.getUserId());
            baseMapper.updateById(collectProduct);

//			// 获取扩展
//			ErpCollectProductExpand expand = erpCollectProductExpandMapper
//					.selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
//							.eq(ErpCollectProductExpand::getCollectProductId, proId).last(" limit 1 "));
//
//			List<ErpCollectProductSku> skuList = erpCollectProductSkuMapper
//					.selectList(new LambdaQueryWrapper<ErpCollectProductSku>()
//							.eq(ErpCollectProductSku::getCollectProductId, proId));
//
//			ErpSellerCollectProduct sellerCollectProduct = new ErpSellerCollectProduct();
//			BeanUtils.copyProperties(collectProduct, sellerCollectProduct);
//
//			// 复制
//			sellerCollectProduct.setId(null);
//			sellerCollectProduct.setCreateTime(null);
//			sellerCollectProduct.setUpdateTime(null);
//			sellerCollectProduct.setCreateBy(LoginHelper.getUserId() + "");
//			sellerCollectProduct.setUpdateBy(LoginHelper.getUserId() + "");
//			sellerCollectProduct.setCollectUserId(LoginHelper.getUserId());
//			erpSellerCollectProductMapper.insert(sellerCollectProduct);
//
//			ErpSellerCollectProductExpand sellerExpand = new ErpSellerCollectProductExpand();
//			BeanUtils.copyProperties(expand, sellerExpand);
//
//			sellerExpand.setId(null);
//			sellerExpand.setCollectProductId(sellerCollectProduct.getId());
//			sellerExpand.setIsFreight(0); // 未运费试算
//			sellerExpand.setIsOptimize(0); // 未优化
//			sellerExpand.setIsTranslate(0); // 未翻译
//			sellerExpand.setEditStatus(0); // 未编辑
//			erpSellerCollectProductExpandMapper.insert(sellerExpand);
//
//			for (ErpCollectProductSku erpCollectProductSku : skuList) {
//
//				ErpSellerCollectProductSku sellerSku = new ErpSellerCollectProductSku();
//				BeanUtils.copyProperties(erpCollectProductSku, sellerSku);
//
//				sellerSku.setId(null);
//				sellerSku.setCollectProductId(sellerCollectProduct.getId());
//				sellerSku.setSkuCode(CommonUtils.getSkuCode()); // 设置新的skucode
//				erpSellerCollectProductSkuMapper.insert(sellerSku);
//			}
//
//			// 判断原来的商品如果没有编辑，就删除
//			Integer editStatus = expand.getEditStatus();
//			if (editStatus.equals(0)) {
//				remList.add(collectProduct.getId());
//			}
        }
//		if (remList.size() > 0) {
//			// 真正删采集商品
//			baseMapper.deleteBatchIds(remList);
//			// 真正删除采集商品的sku
//			erpCollectProductSkuMapper.delete(new LambdaQueryWrapper<ErpCollectProductSku>()
//					.in(ErpCollectProductSku::getCollectProductId, remList));
//			// 真正删除采集商品的扩展类
//			erpCollectProductExpandMapper.delete(new LambdaQueryWrapper<ErpCollectProductExpand>()
//					.in(ErpCollectProductExpand::getCollectProductId, remList));
//		}
    }

    @Override
    public void updateGroundingPro() {

        List<Long> list = new ArrayList<Long>();
        list.add(1658410519802396672l);
        list.add(1673243505958580224l);
        list.add(1677135976323481601l);
        list.add(1646708728982016002l);
        list.add(1655769957540245504l);
        list.add(1673243237108240384l);
        list.add(1661201464987402240l);
        list.add(1658405750016454656l);
        list.add(1681496229079289858l);
        list.add(1661249686533898240l);
        list.add(1674228750432829442l);
        list.add(1658410222921170944l);
        list.add(1673243095034023936l);
        list.add(1676420897626017793l);
        list.add(1681603606982066178l);
        list.add(1673242539654205440l);
        list.add(1661178923302232066l);
        list.add(1651891453921898496l);
        list.add(1673244120352608256l);
        list.add(1658402412828037120l);
        list.add(1648222789758488576l);

        LambdaQueryWrapper<ErpCollectProductExpand> lqw = Wrappers.lambdaQuery();
//		lqw.eq(ErpCollectProductExpand::getProductStatus, 1);

        lqw.in(ErpCollectProductExpand::getCollectProductId, list);

        // 获取已经上架的商品
        List<ErpCollectProductExpand> expandList = erpCollectProductExpandMapper.selectList(lqw);
        for (ErpCollectProductExpand expand : expandList) {
            try {

                // 获取商品信息
                Long collectProductId = expand.getCollectProductId();
                ErpCollectProduct collectProduct = baseMapper.selectById(collectProductId);
                if (collectProduct == null) { // 商品为空，查看个人产品库有误该产品，有就删除
                    List<ErpSellerProduct> sellerProductList = erpSellerProductMapper
                            .selectList(new LambdaQueryWrapper<ErpSellerProduct>()
                                    .eq(ErpSellerProduct::getCollectProductId, collectProductId));
                    List<Long> sellerIds = sellerProductList.stream().map(pro -> pro.getId())
                            .collect(Collectors.toList());
                    if (sellerIds.size() != 0)
                        iErpSellerProductService.deleteWithValidByIds(sellerIds, false);
                    continue;
                }

                List<ErpCollectProductSku> skuList = erpCollectProductSkuMapper
                        .selectList(new LambdaQueryWrapper<ErpCollectProductSku>()
                                .eq(ErpCollectProductSku::getCollectProductId, collectProductId));

                Map<String, BigDecimal> skuMap = new HashMap<>();
                skuList.forEach(sku -> {
                    skuMap.put(sku.getSkuPropertyIds(),
                            new BigDecimal(sku.getSkuPrice()).multiply(new BigDecimal(1.1)));
                });

                // 修改运费试算
                Double min = null;
                Double max = null;

                Map<String, BigDecimal> skuPriceMap = new HashedMap<>();

                // 获取运费，修改金额
                String freightMap = expand.getFreightMap();
                List<Dict> freightMapList = JsonUtils.parseArrayMap(freightMap);
                for (Dict dict : freightMapList) {
                    Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                    String shiptoCountry = (String) dict.get("shiptoCountry");
                    for (String key : absoluteQuoteMap.keySet()) {
                        BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());

                        // 添加sku价格
                        if (skuPriceMap.containsKey(key)) {
                            BigDecimal price = skuPriceMap.get(key);
                            if (price.compareTo(amount) == 1)
                                skuPriceMap.put(key, amount);
                        } else {
                            skuPriceMap.put(key, amount);
                        }

                        // 获取sku
                        BigDecimal skuPrice = skuMap.get(key);

                        // 计算最终价格
                        amount = skuPrice.add(amount).setScale(2, BigDecimal.ROUND_HALF_UP);
                        Double res = amount.doubleValue();
                        absoluteQuoteMap.put(key, res);
                        if (shiptoCountry.equals("US")) {
                            if (min == null || res < min)
                                min = res;
                            if (max == null || res > max)
                                max = res;
                        }

                    }
                }

                // 获取完成的区域定价
                String absoluteQuoteMap = JsonUtils.toJsonString(freightMapList);
                expand.setAbsoluteQuoteMap(absoluteQuoteMap);

                // 修改商品的价格
                collectProduct.setId(collectProductId);
                collectProduct.setProductPrice(min.equals(max) ? min + "" : min + "-" + max);
                baseMapper.updateById(collectProduct);

                // 保存
                erpCollectProductSkuMapper.updateBatchById(skuList);
                erpCollectProductExpandMapper.updateById(expand);

                // 获取个人产品库的列表
                List<ErpSellerProduct> sellerProductList = erpSellerProductMapper
                        .selectList(new LambdaQueryWrapper<ErpSellerProduct>().eq(ErpSellerProduct::getCollectProductId,
                                collectProductId));
                for (ErpSellerProduct sellerProduct : sellerProductList) {

                    // 修改商品的价格
                    sellerProduct.setProductPrice(collectProduct.getProductPrice());
                    erpSellerProductMapper.updateById(sellerProduct);

                    // 修改扩展表的区域定价
                    ErpSellerProductExpand erpSellerProductExpand = erpSellerProductExpandMapper
                            .selectOne(new LambdaQueryWrapper<ErpSellerProductExpand>()
                                    .eq(ErpSellerProductExpand::getSellerProductId, sellerProduct.getId()));
                    erpSellerProductExpand.setAbsoluteQuoteMap(expand.getAbsoluteQuoteMap());
                    erpSellerProductExpandMapper.updateById(erpSellerProductExpand);

                    // 修改sku的价格
                    List<ErpSellerProductSku> sellectSkuList = erpSellerProductSkuMapper
                            .selectList(new LambdaQueryWrapper<ErpSellerProductSku>()
                                    .eq(ErpSellerProductSku::getSellerProductId, sellerProduct.getId()));
                    for (ErpSellerProductSku erpSellerProductSku : sellectSkuList) {
                        String skuPropertyIds = erpSellerProductSku.getSkuPropertyIds();
                        if (skuPriceMap.containsKey(skuPropertyIds)) {
                            BigDecimal minPrice = skuPriceMap.get(skuPropertyIds);

                            // 获取sku
                            BigDecimal skuPrice = skuMap.get(skuPropertyIds);

                            // 计算最终价格
                            BigDecimal amount = skuPrice.add(minPrice.multiply(new BigDecimal(1.5))).setScale(2,
                                    BigDecimal.ROUND_HALF_UP);
                            erpSellerProductSku.setSkuPrice(amount.toString());
                        }
                    }
                    erpSellerProductSkuMapper.updateBatchById(sellectSkuList);
                }
            } catch (Exception e) {
                System.out.println("collectProductId:" + expand.getCollectProductId());
            }

        }

    }


    @Override
    public void updatePersonalGroundingPro() {
        // 获取个人采集已经上架的商品
        List<ErpSellerCollectProduct> list = erpSellerCollectProductMapper.selectGroundingPro();
        for (ErpSellerCollectProduct prod : list) {
            Long productId = prod.getId();
            try {

                // 获取商品信息
                ErpSellerCollectProductExpand expand = erpSellerCollectProductExpandMapper
                        .selectOne(new LambdaQueryWrapper<ErpSellerCollectProductExpand>()
                                .eq(ErpSellerCollectProductExpand::getCollectProductId, productId));

                List<ErpSellerCollectProductSku> skuList = erpSellerCollectProductSkuMapper
                        .selectList(new LambdaQueryWrapper<ErpSellerCollectProductSku>()
                                .eq(ErpSellerCollectProductSku::getCollectProductId, productId));

                Map<String, BigDecimal> skuMap = new HashMap<>();
                Map<String, String> skuCodeMap = new HashMap<>();
                skuList.forEach(sku -> {
                    skuMap.put(sku.getSkuCode(), new BigDecimal(sku.getSkuPrice()).multiply(new BigDecimal(1.1)));
                    skuCodeMap.put(sku.getSkuPropertyIds(), sku.getSkuCode());
                });

                // 修改运费试算
                Double min = null;
                Double max = null;

                Map<String, BigDecimal> skuPriceMap = new HashedMap<>();

                // 获取运费，修改金额
                String freightMap = expand.getFreightMap();
                List<Dict> freightMapList = JsonUtils.parseArrayMap(freightMap);
                for (Dict dict : freightMapList) {
                    Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                    String shiptoCountry = (String) dict.get("shiptoCountry");
                    for (String key : absoluteQuoteMap.keySet()) {
                        BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());

                        String priceKey = skuCodeMap.get(key);

                        // 添加sku价格
                        if (skuPriceMap.containsKey(priceKey)) {
                            BigDecimal price = skuPriceMap.get(priceKey);
                            if (price.compareTo(amount) == 1)
                                skuPriceMap.put(priceKey, amount);
                        } else {
                            skuPriceMap.put(priceKey, amount);
                        }

                        // 获取sku
                        BigDecimal skuPrice = skuMap.get(priceKey);

                        // 计算最终价格
                        amount = skuPrice.add(amount).setScale(2, BigDecimal.ROUND_HALF_UP);
                        Double res = amount.doubleValue();
                        absoluteQuoteMap.put(key, res);
                        if (shiptoCountry.equals("US")) {
                            if (min == null || res < min)
                                min = res;
                            if (max == null || res > max)
                                max = res;
                        }

                    }
                }

                // 获取完成的区域定价
                String absoluteQuoteMap = JsonUtils.toJsonString(freightMapList);
                expand.setAbsoluteQuoteMap(absoluteQuoteMap);

                // 修改商品的价格
                prod.setProductPrice(min.equals(max) ? min + "" : min + "-" + max);
                erpSellerCollectProductMapper.updateById(prod);

                // 保存
                erpSellerCollectProductSkuMapper.updateBatchById(skuList);
                erpSellerCollectProductExpandMapper.updateById(expand);

                // 获取商品信息
                Long collectProductId = productId;
                ErpCollectProduct collectProduct = baseMapper.selectById(collectProductId);
                if (collectProduct == null) { // 商品为空，查看个人产品库有误该产品，有就删除
                    List<ErpSellerProduct> sellerProductList = erpSellerProductMapper
                            .selectList(new LambdaQueryWrapper<ErpSellerProduct>()
                                    .eq(ErpSellerProduct::getCollectProductId, collectProductId));
                    List<Long> sellerIds = sellerProductList.stream().map(pro -> pro.getId())
                            .collect(Collectors.toList());
                    if (sellerIds.size() != 0)
                        iErpSellerProductService.deleteWithValidByIds(sellerIds, false);
                    continue;
                }

                ErpCollectProductExpand expand1 = erpCollectProductExpandMapper
                        .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                                .eq(ErpCollectProductExpand::getCollectProductId, productId));

                List<ErpCollectProductSku> skuList1 = erpCollectProductSkuMapper
                        .selectList(new LambdaQueryWrapper<ErpCollectProductSku>()
                                .eq(ErpCollectProductSku::getCollectProductId, collectProductId));

                Map<String, BigDecimal> skuMap1 = new HashMap<>();
                skuList1.forEach(sku -> {
                    skuMap1.put(sku.getSkuPropertyIds(),
                            new BigDecimal(sku.getSkuPrice()).multiply(new BigDecimal(1.1)));
                });

                Map<String, BigDecimal> skuPriceMap1 = new HashedMap<>();

                // 获取运费，修改金额
                String freightMap1 = expand1.getFreightMap();
                List<Dict> freightMapList1 = JsonUtils.parseArrayMap(freightMap1);
                for (Dict dict : freightMapList1) {
                    Map<String, Object> absoluteQuoteMap1 = (Map) dict.get("absoluteQuoteMap");
                    String shiptoCountry = (String) dict.get("shiptoCountry");
                    for (String key : absoluteQuoteMap1.keySet()) {
                        BigDecimal amount = new BigDecimal(absoluteQuoteMap1.get(key).toString());

                        // 添加sku价格
                        if (skuPriceMap1.containsKey(key)) {
                            BigDecimal price = skuPriceMap1.get(key);
                            if (price.compareTo(amount) == 1)
                                skuPriceMap1.put(key, amount);
                        } else {
                            skuPriceMap1.put(key, amount);
                        }

                        // 获取sku
                        BigDecimal skuPrice = skuMap1.get(key);

                        // 计算最终价格
                        amount = skuPrice.add(amount).setScale(2, BigDecimal.ROUND_HALF_UP);
                        Double res = amount.doubleValue();
                        absoluteQuoteMap1.put(key, res);
                        if (shiptoCountry.equals("US")) {
                            if (min == null || res < min)
                                min = res;
                            if (max == null || res > max)
                                max = res;
                        }

                    }
                }

                // 获取完成的区域定价
                String absoluteQuoteMap1 = JsonUtils.toJsonString(freightMapList1);
                expand1.setAbsoluteQuoteMap(absoluteQuoteMap1);

                // 修改商品的价格
                collectProduct.setId(collectProductId);
                collectProduct.setProductPrice(min.equals(max) ? min + "" : min + "-" + max);
                baseMapper.updateById(collectProduct);

                // 保存
                erpCollectProductSkuMapper.updateBatchById(skuList1);
                erpCollectProductExpandMapper.updateById(expand1);

                // 获取个人产品库的列表
                List<ErpSellerProduct> sellerProductList = erpSellerProductMapper
                        .selectList(new LambdaQueryWrapper<ErpSellerProduct>().eq(ErpSellerProduct::getCollectProductId,
                                collectProductId));
                for (ErpSellerProduct sellerProduct : sellerProductList) {

                    // 修改商品的价格
                    sellerProduct.setProductPrice(collectProduct.getProductPrice());
                    erpSellerProductMapper.updateById(sellerProduct);

                    // 修改扩展表的区域定价
                    ErpSellerProductExpand erpSellerProductExpand = erpSellerProductExpandMapper
                            .selectOne(new LambdaQueryWrapper<ErpSellerProductExpand>()
                                    .eq(ErpSellerProductExpand::getSellerProductId, sellerProduct.getId()));
                    erpSellerProductExpand.setAbsoluteQuoteMap(expand1.getAbsoluteQuoteMap());
                    erpSellerProductExpandMapper.updateById(erpSellerProductExpand);

                    // 修改sku的价格
                    List<ErpSellerProductSku> sellectSkuList = erpSellerProductSkuMapper
                            .selectList(new LambdaQueryWrapper<ErpSellerProductSku>()
                                    .eq(ErpSellerProductSku::getSellerProductId, sellerProduct.getId()));
                    for (ErpSellerProductSku erpSellerProductSku : sellectSkuList) {
                        String skuPropertyIds = erpSellerProductSku.getSkuPropertyIds();
                        if (skuPriceMap1.containsKey(skuPropertyIds)) {
                            BigDecimal minPrice = skuPriceMap1.get(skuPropertyIds);

                            // 获取sku
                            BigDecimal skuPrice = skuMap1.get(skuPropertyIds);

                            // 计算最终价格
                            BigDecimal amount = skuPrice.add(minPrice.multiply(new BigDecimal(1.5))).setScale(2,
                                    BigDecimal.ROUND_HALF_UP);
                            erpSellerProductSku.setSkuPrice(amount.toString());
                        }
                    }
                    erpSellerProductSkuMapper.updateBatchById(sellectSkuList);
                }

            } catch (Exception e) {
                System.out.println("productId:" + productId);
            }

        }

    }

    @Override
    public void splitPro() {

        // 获取已经运费试算的商品
        LambdaQueryWrapper<ErpCollectProductFreightTask> lqw = Wrappers.lambdaQuery();
        lqw.eq(ErpCollectProductFreightTask::getStatus, 2);
        lqw.eq(ErpCollectProductFreightTask::getType, 1);
//		lqw.le(ErpCollectProductFreightTask::getId, 1650789460435886082l);
        //TODO 运费相关 内部类调用
//        List<ErpCollectProductFreightTask> list = erpCollectProductFreightTaskMapper.selectList(lqw);
        List<ErpCollectProductFreightTask> list = null;

        // 拆分商品
        for (ErpCollectProductFreightTask task : list) {

            Long collectProductId = task.getCollectProductId();
            // Long collectProductId = 1650789460435886082l;
            System.out.println("CollectProductId: " + collectProductId);

            // 获取商品
            ErpCollectProduct collectProduct = baseMapper.selectById(collectProductId);
            if (collectProduct == null) {
                continue;
            }
            // 获取
            ErpCollectProductExpand collectProductExpand = erpCollectProductExpandMapper
                    .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                            .eq(ErpCollectProductExpand::getCollectProductId, collectProductId));

            if (collectProductExpand == null)
                continue;

            // 获取采集商品sku
            List<ErpCollectProductSku> skuList = erpCollectProductSkuMapper
                    .selectList(new LambdaQueryWrapper<ErpCollectProductSku>()
                            .eq(ErpCollectProductSku::getCollectProductId, collectProductId));
            if (skuList == null || skuList.size() == 0)
                continue;
            //TODO 运费相关 内部类调用
            //erpCollectProductFreightTaskService.measureSplitCollectPro(skuList, collectProductExpand);
        }

    }


    @Override
    public boolean updateProductImgAndDel(ErpCollectProductBo collectProduct) {
        Long id = collectProduct.getId();
        ErpCollectProduct erpCollectProduct = baseMapper.selectById(id);
        if (collectProduct.getEditStatus() == 1) {
            // 删除老图片
            String pastMarketing = erpCollectProduct.getMarketing();
            String imageURLs = erpCollectProduct.getImageURLs();
            String white = erpCollectProduct.getWhite();
            String detail = erpCollectProduct.getDetailImg();

            // 加入新图片
            erpCollectProduct.setMarketing(urlsToOssUrls(erpCollectProduct.getMarketing()));
            erpCollectProduct.setImageURLs(urlsToOssUrls(erpCollectProduct.getImageURLs()));
            erpCollectProduct.setWhite(urlsToOssUrls(erpCollectProduct.getWhite()));
            erpCollectProduct.setDetailImg(urlsToOssUrls(erpCollectProduct.getDetailImg()));

            delALiYunPic(pastMarketing);
            delALiYunPic(imageURLs);
            delALiYunPic(white);
            delALiYunPic(detail);
        } else {
            // 加入新图片
            erpCollectProduct.setMarketing(collectProduct.getMarketing());
            erpCollectProduct.setImageURLs(collectProduct.getImageURLs());
            erpCollectProduct.setWhite(collectProduct.getWhite());
            erpCollectProduct.setDetailImg(collectProduct.getDetailImg());
        }

        return baseMapper.updateById(erpCollectProduct) > 0;
    }

    /**
     * 删除阿里云临时图片
     *
     * @param urls
     */
    public void delALiYunPic(String urls) {
        R<Object> returnObj = remoteFileService.delALiYunPic(urls);
    }

    @Override
    public R<Object> generateWhite(String imgUrl) {
        //TODO OSS相关 待测试
        //自动抠图
        String handle = urlConfig.getHandle();
        ResponseEntity<String> forEntity = restTemplate.getForEntity(
                handle + "/medium/remove/background?sourceImgUrl=" + imgUrl, String.class);
        String body = forEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        Integer code = jsonObject.getInteger("code");
        if (200 != code) {
            return R.fail("生成失败");
        } else {
            String url = jsonObject.getString("data");

            // 进行套图，和白底图标签中的白底图进行套图
            ErpProductAtlas atlas = erpProductAtlasMapper.selectOne(
                    new LambdaQueryWrapper<ErpProductAtlas>().eq(ErpProductAtlas::getTagId, 1650776561517563905L));
            if (ObjectUtils.isEmpty(atlas)) {
                return R.fail("白底图背景为空");
            }
            String backgroundPic = "https://file.pbb2c.com/" + atlas.getPictureUrl();
            String elementPic = url;
            String newPicUrl = urlConfig.getTempPicPath() + "" + IdUtil.fastSimpleUUID() + ".jpg";
            ImageMergeUtils.overlyingImageTest(backgroundPic, elementPic, newPicUrl);
            String mergeUrl = uploadNewPicToOss(newPicUrl);
            System.out.println(mergeUrl);
            return R.ok(mergeUrl);
        }
    }

    @Override
    public R<Object> generateMarketing(String imgUrl) {
        //TODO OSS相关 待测试
        //自动抠图
        String handle = urlConfig.getHandle();
        ResponseEntity<String> forEntity = restTemplate.getForEntity(
                handle + "/medium/remove/background?sourceImgUrl=" + imgUrl, String.class);
        String body = forEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        Integer code = jsonObject.getInteger("code");
        if (200 != code) {
            return R.fail("生成失败");
        } else {
            String url = jsonObject.getString("data");

            // 进行套图，和白底图标签中的白底图进行套图
            ErpProductAtlas atlas = erpProductAtlasMapper.selectOne(new LambdaQueryWrapper<ErpProductAtlas>()
                    .eq(ErpProductAtlas::getTagId, 1734451666229985281L).last("ORDER BY RAND() LIMIT 1"));
            if (ObjectUtils.isEmpty(atlas)) {
                return R.fail("营销图背景为空");
            }
            String backgroundPic = "https://file.pbb2c.com/" + atlas.getPictureUrl();
            String elementPic = url;
            String newPicUrl = urlConfig.getTempPicPath() + "" + IdUtil.fastSimpleUUID() + ".jpg";
            ImageMergeUtils.overlyingImageTest(backgroundPic, elementPic, newPicUrl);
            String mergeUrl = uploadNewPicToOss(newPicUrl);
            System.out.println(mergeUrl);
            return R.ok(mergeUrl);
        }
    }

    @Override
    public R<Object> autoGenerateMarketingOrWhite(String collectProductId) {
        //TODO oss相关 待测试
        ErpCollectProduct product = baseMapper.selectById(collectProductId);
        if (ObjectUtils.isNull(product)) {
            return R.fail("商品不存在");
        }
        //白底图
        String whiteImg = null;
        String marketImg = null;
        if (ObjectUtils.isNull(product.getWhite())) {
            //若白底图为空，则自动选择一张图片作为白底图
            List<String> list = Arrays.asList(product.getImageURLs().split(";"));
            for (String img : list) {
                String ossImg = "https://file.pbb2c.com/" + urlsToOssUrls(img);
                ImageReader reader = ImageIO.getImageReadersByFormatName("JPEG").next();
                BufferedImage image = null;
                try {
                    reader.setInput(ImageIO.createImageInputStream(ossImg), true);
                    ImageReadParam param = reader.getDefaultReadParam();
                    image = reader.read(0, param);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                int width = image.getWidth();
                int height = image.getHeight();
                System.out.println("Width: " + width + ", Height: " + height);
                if (width == 800 && height == 800) {
                    whiteImg = img;
                    break;
                } else if (width == 640 && height == 640) {
                    whiteImg = img;
                    break;
                } else if (width == 1000 && height == 1000) {
                    whiteImg = img;
                    break;
                }
            }
            if (ObjectUtils.isNull(whiteImg)) {
                //没有符合尺寸要求的
                //随机第一张
                whiteImg = list.get(0);
            }

            //调用方法抠图
            R<Object> objectR = generateWhite(whiteImg);
            if (objectR.getCode() != 200) {
                //抠图失败
                return R.fail("白底图抠图失败，请手动选择抠图或上传白底图");
            } else {
                whiteImg = (String) objectR.getData();
            }
        }

        if (ObjectUtils.isNull(product.getMarketing())) {
            //生成营销图
            R<Object> objectR = generateMarketing(whiteImg);
            if (objectR.getCode() != 200) {
                //抠图失败
                return R.fail("营销图抠图失败，请手动选择抠图或上传营销图");
            } else {
                marketImg = (String) objectR.getData();
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("marketImg", marketImg);
        map.put("whiteImg", whiteImg);
        return R.ok(map);
    }

    @Override
    public void updateCategoryInfo(ErpCollectProduct product) {
        String subject = product.getSubject();
        // 根据标题获取类目
        Map<String, Object> map = new HashMap<>();
        map.put("title", subject);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://47.94.131.193:8000/product/getCidByTitle", map, String.class);
        String body = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        Integer code = jsonObject.getInteger("code");
        if (code == 200) {
            JSONArray dataArray = jsonObject.getJSONArray("data");
            if (dataArray.size() != 0) {
                Long id = dataArray.getJSONObject(0).getLong("id");
                if (id != null) {
                    product.setCategoryId(id);
                    baseMapper.updateById(product);
                }
//                // 获取商品属性列表，填空
//                List<Aliexpress.CategoryInfoVo> categoryInfoByIdList =
//                        aliexpressCategoryServiceImpl.getCategoryInfoById(id, false);
//                Map<String, Object> attrMap = new HashMap<>();
//                List<Map<String, Object>> list = new ArrayList<>();
//                for (Aliexpress.CategoryInfoVo categoryInfoVo : categoryInfoByIdList) {
//                    String required = categoryInfoVo.getRequired();
//                    if (required.equals("1")) { // 是必填项
//                        String attributeShowTypeValue = categoryInfoVo.getAttributeShowTypeValue();
//                        // 产地都是大陆
//                        if (categoryInfoVo.getAttr_name_id() == 219) {
//                            attrMap = new HashMap<>();
//                            attrMap.put("attr_name", "Origin");
//                            attrMap.put("attr_name_id", 219);
//                            attrMap.put("attr_value", null);
//                            attrMap.put("attr_value_id", 9441741844L);
//                            list.add(attrMap);
//                            continue;
//                        }
//                        switch (attributeShowTypeValue) {
//                            case "list_box":
//                                // 下拉框，默认选第一个
//                                attrMap = new HashMap<>();
//                                attrMap.put("attr_name", categoryInfoVo.getAttr_name());
//                                attrMap.put("attr_name_id", categoryInfoVo.getAttr_name_id());
//                                attrMap.put("attr_value", null);
//                                attrMap.put("attr_value_id", categoryInfoVo.getValues().get(0).getAttr_value_id());
//                                list.add(attrMap);
//                                break;
//                            case "input":
//                                attrMap = new HashMap<>();
//                                attrMap.put("attr_name", null);
//                                attrMap.put("attr_name_id", categoryInfoVo.getAttr_name_id());
//                                attrMap.put("attr_value", "1");
//                                attrMap.put("attr_value_id", null);
//                                list.add(attrMap);
//                                break;
//                        }
//                    }
//                }
//
//                // 保存产品属性
//                String customAttributes = JSONObject.toJSONString(list);
//                product.setCustomAttributes(customAttributes);
//                baseMapper.updateById(product);
            }
            // 保存完需要改变状态
            ErpCollectProductExpand collectProductExpand = erpCollectProductExpandMapper.selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                    .eq(ErpCollectProductExpand::getCollectProductId, product.getId()));
            collectProductExpand.setIsAutoOptimize(1);
            erpCollectProductExpandMapper.updateById(collectProductExpand);
        } else {
            ErpCollectProductExpand collectProductExpand = erpCollectProductExpandMapper.selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                    .eq(ErpCollectProductExpand::getCollectProductId, product.getId()));
            collectProductExpand.setIsAutoOptimize(2);
            collectProductExpand.setAutoOptimizeRemark("根据标题获取类目失败，" + body);
            erpCollectProductExpandMapper.updateById(collectProductExpand);
        }
    }


    @Override
    public void updateCustomAttributesByCategory(Long productId) {
        ErpCollectProduct product = baseMapper.selectById(productId);
        if (product == null)
            return;
        // 判断类目是不是空
        if (product.getCategoryId() == null) {
            return;
        }
        // 排除不是最底级类目
        Boolean bottomLevel = erpCollectProductCategoryService.judgeIsBottomLevel(product.getCategoryId());
        if (!bottomLevel) {
            return;
        }
        // 获取商品属性列表，填空
        //TODO 内部类调用
        List<Aliexpress.CategoryInfoVo> categoryInfoByIdList =
                aliexpressCategoryService.getCategoryInfoById(product.getCategoryId(), false);
        if (categoryInfoByIdList.size() == 0)
            return;
        Map<String, Object> attrMap = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        for (Aliexpress.CategoryInfoVo categoryInfoVo : categoryInfoByIdList) {
            String required = categoryInfoVo.getRequired();
            if (required.equals("1")) { // 是必填项
                String attributeShowTypeValue = categoryInfoVo.getAttributeShowTypeValue();
                // 产地都是大陆
                if (categoryInfoVo.getAttr_name_id() == 219) {
                    attrMap = new HashMap<>();
                    attrMap.put("attr_name", "Origin");
                    attrMap.put("attr_name_id", 219);
                    attrMap.put("attr_value", null);
                    attrMap.put("attr_value_id", 9441741844L);
                    list.add(attrMap);
                    continue;
                }
                switch (attributeShowTypeValue) {
                    case "list_box":
                        // 下拉框，默认选第一个
                        attrMap = new HashMap<>();
                        attrMap.put("attr_name", categoryInfoVo.getAttr_name());
                        attrMap.put("attr_name_id", categoryInfoVo.getAttr_name_id());
                        attrMap.put("attr_value", null);
                        attrMap.put("attr_value_id", categoryInfoVo.getValues().get(0).getAttr_value_id());
                        list.add(attrMap);
                        break;
                    case "input":
                        attrMap = new HashMap<>();
                        attrMap.put("attr_name", null);
                        attrMap.put("attr_name_id", categoryInfoVo.getAttr_name_id());
                        attrMap.put("attr_value", "1");
                        attrMap.put("attr_value_id", null);
                        list.add(attrMap);
                        break;
                    case "check_box":
                        attrMap = new HashMap<>();
                        attrMap.put("attr_name", categoryInfoVo.getAttr_name());
                        attrMap.put("attr_name_id", categoryInfoVo.getAttr_name_id());
                        attrMap.put("attr_value", "1");
                        attrMap.put("attr_value_id", categoryInfoVo.getValues().get(0).getAttr_value_id());
                        list.add(attrMap);
                        break;
//                    case "interval":
//                    case "brand":
                }
            }
        }

        // 保存产品属性
        String customAttributes = JSONObject.toJSONString(list);
        product.setCustomAttributes(customAttributes);
        int update = baseMapper.updateById(product);
        ErpCollectProductExpand collectProductExpand = erpCollectProductExpandMapper.selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                .eq(ErpCollectProductExpand::getCollectProductId, product.getId()));

        if (update > 0) {
            collectProductExpand.setIsAutoOptimize(1);
            collectProductExpand.setAutoOptimizeRemark("填写产品属性成功");
        } else {
            collectProductExpand.setIsAutoOptimize(2);
            collectProductExpand.setAutoOptimizeRemark("填写产品属性失败");
        }
        erpCollectProductExpandMapper.updateById(collectProductExpand);
    }

    @Override
    public R<Object> getCollectProductCategoryInfo(Long collectId) {
        ErpCollectProduct collectProduct = baseMapper.selectById(collectId);
        if (ObjectUtils.isNotNull(collectProduct)) {
            Long categoryId = collectProduct.getCategoryId();
            ErpCollectProductCategory category = collectProductCategoryMapper.selectById(categoryId);
            Map<String, Object> map = new HashMap<>();
            map.put("categoryId", categoryId);
            map.put("name", category.getName());
            return R.ok(map);
        } else {
            return R.fail("商品不存在");
        }
    }

    @Override
    public R<Object> deleteDuplicateProductThree() {
        List<String> skuCodeList = erpCollectProductSkuMapper.deleteDuplicateCollectProductId();
        if (skuCodeList.size() == 0) {
            return R.fail();
        }

        Map<Long, Object> map = new HashMap<>();
        int i = 0;
        Boolean flagType = false;
        for (String skuCode : skuCodeList) {

            i++;
            System.out.println(i);

            List<ErpCollectProductSku> skuList = erpCollectProductSkuMapper.selectList(
                    new LambdaQueryWrapper<ErpCollectProductSku>()
                            .eq(ErpCollectProductSku::getSkuCode, skuCode)
                            .eq(ErpCollectProductSku::getDelFlag, 0)
            );

            ErpCollectProductExpand proOne = erpCollectProductExpandMapper.selectOne(
                    new LambdaQueryWrapper<ErpCollectProductExpand>()
                            .eq(ErpCollectProductExpand::getCollectProductId, skuList.get(0).getCollectProductId())
            );
            Long collectProductIdOne = proOne.getCollectProductId();
            if (ObjectUtils.isNotNull(map.get(collectProductIdOne))) {
                continue;
            } else {
                map.put(collectProductIdOne, skuCode);
            }
            Integer delFlagOne = Integer.valueOf(proOne.getDelFlag());


            ErpCollectProductExpand proTwo = erpCollectProductExpandMapper.selectOne(
                    new LambdaQueryWrapper<ErpCollectProductExpand>()
                            .eq(ErpCollectProductExpand::getCollectProductId, skuList.get(1).getCollectProductId())
            );
            Long collectProductIdTwo = proTwo.getCollectProductId();
            if (ObjectUtils.isNotNull(map.get(collectProductIdTwo))) {
                continue;
            } else {
                map.put(collectProductIdTwo, skuCode);
            }
            Integer delFlagTwo = Integer.valueOf(proTwo.getDelFlag());

            ErpCollectProductExpand proThree = erpCollectProductExpandMapper.selectOne(
                    new LambdaQueryWrapper<ErpCollectProductExpand>()
                            .eq(ErpCollectProductExpand::getCollectProductId, skuList.get(2).getCollectProductId())
            );
            Long collectProductIdThree = proThree.getCollectProductId();
            if (ObjectUtils.isNotNull(map.get(collectProductIdThree))) {
                continue;
            } else {
                map.put(collectProductIdThree, skuCode);
            }
            Integer delFlagThree = Integer.valueOf(proThree.getDelFlag());

            int delCount = delFlagOne + delFlagTwo + delFlagThree;
            //分情况
            if (delCount == 0) {
                //1、三不删
                Integer statusOne = proOne.getProductStatus();
                Integer statusTwo = proTwo.getProductStatus();
                Integer statusThree = proThree.getProductStatus();
                Integer statusFlag = statusOne + statusTwo + statusThree;
                // - 1 ABC都上架/都不上架 选最新
                if (statusFlag == 3 || statusFlag == 0) {
                    Date updateTimeOne = proOne.getUpdateTime();
                    Date updateTimeTwo = proTwo.getUpdateTime();
                    Date updateTimeThree = proThree.getUpdateTime();
                    LocalDateTime localDateTimeOne = updateTimeOne.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                    LocalDateTime localDateTimeTwo = updateTimeTwo.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                    LocalDateTime localDateTimeThree = updateTimeThree.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                    List<LocalDateTime> dateTimes = Arrays.asList(localDateTimeOne, localDateTimeTwo, localDateTimeThree);
                    LocalDateTime latestDateTime = dateTimes.stream().max(LocalDateTime::compareTo).orElse(null);

                    if (latestDateTime.toString().equals(localDateTimeOne.toString())) {
                        //一号最新
                        proTwo.setDelFlag("2");
                        proTwo.setProductStatus(0);
                        proThree.setDelFlag("2");
                        proThree.setProductStatus(0);
                        erpCollectProductExpandMapper.updateById(proTwo);
                        erpCollectProductExpandMapper.updateById(proThree);
                    } else if (latestDateTime.toString().equals(localDateTimeTwo.toString())) {
                        //二号最新
                        proOne.setDelFlag("2");
                        proOne.setProductStatus(0);
                        proThree.setDelFlag("2");
                        proThree.setProductStatus(0);
                        erpCollectProductExpandMapper.updateById(proOne);
                        erpCollectProductExpandMapper.updateById(proThree);
                    } else if (latestDateTime.toString().equals(localDateTimeThree.toString())) {
                        //二号最新
                        proTwo.setDelFlag("2");
                        proTwo.setProductStatus(0);
                        proOne.setDelFlag("2");
                        proOne.setProductStatus(0);
                        erpCollectProductExpandMapper.updateById(proOne);
                        erpCollectProductExpandMapper.updateById(proTwo);
                    }
                    continue;
                }
                // - 2 两上一不上 两个上架的选最新
                if (statusFlag == 2) {
                    if (statusOne == 0) {
                        deleteDuplicateProductMethod(proTwo, proThree);
                    } else if (statusTwo == 0) {
                        deleteDuplicateProductMethod(proOne, proThree);
                    } else if (statusThree == 0) {
                        deleteDuplicateProductMethod(proOne, proTwo);
                    }
                    continue;
                }

                // - 3 一上两不上 选一上
                if (statusFlag == 1) {
                    if (statusOne == 1) {
                        proTwo.setDelFlag("2");
                        proTwo.setProductStatus(0);
                        proThree.setDelFlag("2");
                        proThree.setProductStatus(0);
                        erpCollectProductExpandMapper.updateById(proTwo);
                        erpCollectProductExpandMapper.updateById(proThree);
                    } else if (statusTwo == 1) {
                        proOne.setDelFlag("2");
                        proOne.setProductStatus(0);
                        proThree.setDelFlag("2");
                        proThree.setProductStatus(0);
                        erpCollectProductExpandMapper.updateById(proOne);
                        erpCollectProductExpandMapper.updateById(proThree);
                    } else if (statusThree == 1) {
                        proTwo.setDelFlag("2");
                        proTwo.setProductStatus(0);
                        proOne.setDelFlag("2");
                        proOne.setProductStatus(0);
                        erpCollectProductExpandMapper.updateById(proTwo);
                        erpCollectProductExpandMapper.updateById(proOne);
                    }
                    continue;
                }
            } else if (delCount == 2) {
                //一删两不删
                //排除一删，走老方法
                if (delFlagOne == 0 && delFlagTwo == 0) {
                    deleteDuplicateProductMethod(proOne, proTwo);
                } else if (delFlagOne == 0 && delFlagThree == 0) {
                    deleteDuplicateProductMethod(proOne, proThree);
                } else if (delFlagTwo == 0 && delFlagThree == 0) {
                    deleteDuplicateProductMethod(proTwo, proThree);
                }
            } else if (delCount == 4) {
                //两删一不删
                //选不删的
                if (delFlagOne == 0) {
                    proTwo.setDelFlag("2");
                    proThree.setDelFlag("2");
                    erpCollectProductExpandMapper.updateById(proTwo);
                    erpCollectProductExpandMapper.updateById(proThree);
                } else if (delFlagTwo == 0) {
                    proOne.setDelFlag("2");
                    proThree.setDelFlag("2");
                    erpCollectProductExpandMapper.updateById(proOne);
                    erpCollectProductExpandMapper.updateById(proThree);
                } else if (delFlagThree == 0) {
                    proTwo.setDelFlag("2");
                    proOne.setDelFlag("2");
                    erpCollectProductExpandMapper.updateById(proTwo);
                    erpCollectProductExpandMapper.updateById(proOne);
                }
            }


        }
        return null;
    }

    public R<Object> deleteDuplicateProductMethod(ErpCollectProductExpand proOne, ErpCollectProductExpand proTwo) {
        //看是否上架
        Boolean flagType = false;

        Integer productStatusOne = proOne.getProductStatus();
        Integer productStatusTwo = proTwo.getProductStatus();

        int flag = proOne.getCreateTime().compareTo(proTwo.getCreateTime());
        if (productStatusOne == 1 && productStatusTwo == 1) {
            //都为上架时
            String classOne = proOne.getClassifyLabel();
            String classTwo = proTwo.getClassifyLabel();

            if (ObjectUtils.isNotNull(classOne) && ObjectUtils.isNull(classTwo)) {
                proOne.setDelFlag("2");
                proTwo.setDelFlag("0");
                flagType = true;
            } else if (ObjectUtils.isNotNull(classTwo) && ObjectUtils.isNull(classOne)) {
                proOne.setDelFlag("0");
                proTwo.setDelFlag("2");
                flagType = true;
            } else {
                //按时间保留
                if (flag >= 0) {
                    //说明proTwo的时间早于proOne
                    //留proTwo
                    proOne.setProductStatus(0);
                    proOne.setDelFlag("2");
                    proTwo.setProductStatus(1);
                    proTwo.setDelFlag("0");
                    flagType = true;
                } else {
                    proOne.setProductStatus(1);
                    proOne.setDelFlag("0");
                    proTwo.setProductStatus(0);
                    proTwo.setDelFlag("2");
                    flagType = true;
                }
            }
        } else if (productStatusOne == 0 && productStatusTwo == 0) {
            //都不为上架时
            String classOne = proOne.getClassifyLabel();
            String classTwo = proTwo.getClassifyLabel();

            if (ObjectUtils.isNotNull(classOne) && ObjectUtils.isNull(classTwo)) {
                proOne.setDelFlag("2");
                proTwo.setDelFlag("0");
                flagType = true;
            } else if (ObjectUtils.isNotNull(classTwo) && ObjectUtils.isNull(classOne)) {
                proOne.setDelFlag("0");
                proTwo.setDelFlag("2");
                flagType = true;
            } else {
                if (flag >= 0) {
                    //说明proTwo的时间早于proOne
                    //留proTwo
                    proOne.setDelFlag("2");
                    proTwo.setDelFlag("0");
                    flagType = true;
                } else {
                    proOne.setDelFlag("0");
                    proTwo.setDelFlag("2");
                    flagType = true;
                }
            }
        } else if (productStatusOne == 0 && productStatusTwo == 1) {
            //one上架了，two没上架
            proOne.setDelFlag("2");
            proTwo.setDelFlag("0");
            flagType = true;
        } else if (productStatusOne == 1 && productStatusTwo == 0) {
            //two上架了，one没上架
            proOne.setDelFlag("0");
            proTwo.setDelFlag("2");
            flagType = true;
        }


        if (flagType) {

            erpCollectProductExpandMapper.updateById(proOne);
            erpCollectProductExpandMapper.updateById(proTwo);
            flagType = false;
        }


        return R.ok();
    }

    /**
     * 根据图片地址，上传图片
     *
     * @param newPicUrl
     * @return
     */
    private String uploadNewPicToOss(String newPicUrl) {
        //TODO 内部类调用

        File file = new File(newPicUrl);
        String name = file.getName();
        InputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        MultipartFile multipartFile = null;
        try {
            multipartFile = new MockMultipartFile(name, name, ContentType.APPLICATION_OCTET_STREAM.toString(),
                    fileInputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        R<Object> fileR = remoteFileService.uploadOss(multipartFile);
        String fileRString = JSONObject.toJSONString(fileR.getData());
        SysOssVo upload = JSONObject.parseObject(fileRString, SysOssVo.class);
        // 删除临时图片
        file.delete();
        return upload.getUrl();
    }


}
